CakePHP 3.3.9 Rest API with File not working

File uploads work when I am using postman but when I am using CAKEPHP project (Http Client) for only data it’s work but with file not working

Cakephp Client : Only Data without File ( it’s working )

Cakephp Client : Data with File ( does not work )

Postman : Data with File ( it’s working )

in /config/routes.php

$routes->extensions(['json','xml']);

Code :

 use CakeHttpClient;
 use CakeHttpClientFormData;
    
   public function add()
    {
        $client = $this->Clients->newEntity();
        if ($this->request->is('post')) {
            $client = $this->Clients->patchEntity($client, $this->request->data);
            if ($this->Clients->save($client)) {

                    $formData = new FormData();
                    $formData->addMany($this->request->data);
     
                      $file = $formData->addFile('header_file',fopen($this->request->data['header_file']['tmp_name'], 'r'));
                      $file->contentId($this->request->data['header_file']['name']);
                      $file->disposition('attachment');
                               
                    $options = [
                         'headers' => ['Content-Type' => $formData->contentType()]                   
                     ];
                
                    $http = new Client(); 
                    $url = 'http://example.com/clients/add.json';
                    $result = $http->post($url,(string)$formData,$options);
                    var_dump($result);
                    exit;
               }
}

Thanks, I use cakephp 3.3.9 sorry for bad English.

Change the date by one day on date picker

Hello I have created a booking form with html and can’t find how to make it so that the check out datepicker value always be the next day that is selected on the check in datepicker.

I have already tried to input the date of the check in datepicker to a var and print it to the value of the date picker but didn’t work.

I will be placed on a wordpress shortcode widget.

This is the one of the codes I have tried.

    <html>
    <body>
<form method="get">
    <script type="date/javascript">
            var indate = document.getElementById(Check_In_Date);
            var outdate = document.setElementById(Check_Out_Date);
            
            outdate.value="indate";
            </script>
    
        <font>&nbsp&nbsp&nbsp&nbsp&nbsp Check In Date &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp Check Out Date&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <br></font>
        &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
        <input type="date" name="checkin" id="Check_In_Date" value="2022-05-16" >                             
        
        <input type="date" name="checkout" id="Check_Out_Date" value="outdate">
        
            <select name="adults">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select>
            
            
        <select name="children">
            <option value="0">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
        
    <input type="submit" value="Search">
</form>
    <body>
    </html>

Best way to make multiple update with PDO

I need to update my table with multiple request.
With a form, i get some values that i will take for update my table.

  $products =  [
    'prodotto1' => [
      'referenza' => $_POST['referenza1'],
      'prezzo' => $_POST['prezzo1'],
    ],
    'prodotto2' => [
      'referenza' => $_POST['referenza2'],
      'prezzo' => $_POST['prezzo2'],
    ],
    'prodotto3' => [
      'referenza' => $_POST['referenza3'],
      'prezzo' => $_POST['prezzo3'],
    ]
  ];

I thought to do this with a foreach :

function updateProducts(array $params){
$pdo = $GLOBALS["db"];
$sql = "UPDATE product SET REFERENCE=:reference, PRICE=:price WHERE REFERENCE=:reference";
$stmt= $pdo->prepare($sql);

foreach ($params as $prodotto ){
    if ($prodotto['referenza'] && $prodotto['prezzo'] ){
        $stmt->bindParam(':reference', $prodotto['referenza'], PDO::PARAM_STR);
        $stmt->bindParam(':price', $prodotto['prezzo']);
        $stmt->execute();

    }
}

}

But i’m not sure that is the best way to do this.

Can u suggest me some goods practice ?

Undefined variable in php while insert to mysql [duplicate]

I am getting this error that the variable is undefined when I actually set it to the value and no matter what kind of value I set even simple $user = 1 ; doesn’t work and I got error it is undefined

<?php 

session_start();

include ('get-user-data.php');

$user = array();

if(isset($_SESSION['userID'])){
    require ('connection.php');
    $userId = $_SESSION['userID'];


    function wantToRead() {
        $query = " INSERT INTO bookshelf (id, tittle, category, thumbnail) VALUES ('$userId', ' Book', 'read')";
    }
}
?>

So I hava a small online shop project :( Uncaught Error: Call to undefined function mysql_connect() can anyone help me connect to database [duplicate]

so I do everything same with the tutorial but it’s end up getting
Uncaught Error: Call to undefined function mysql_connect()

**But I someguy told I need to change to sqli instead **
I’m not good with coding but I have to do this small project by myself

and some other php file too.
I’ll have download link for you too work with please help 🙁

http://www.mediafire.com/file/2bmmao9ibbjpwzv/plaincart.rar/file
database file is in library

WordPress shortecode

I am using myCred on my site. Specially myCred transfer. There is an existing shortcode for this particular plugin.
[mycred_transfer pay_to=1]
where pay_to is the recipient wordpress user id. I can only manually add a user id. But so I need to manually create a shortcode for every created user and it is no go :D.
so therefore I created this function to gather user id of the current post.

// Shortcode to output custom PHP
function author_id( $atts ) {
   echo $user_id = get_the_author_meta( 'ID' );
}
add_shortcode( 'my_author_id', 'author_id');

and it works for the user ID. but do not know how to replace it “1” in [mycred_transfer pay_to=1]
because if I replace “1” with a shortcode it does not work.
Thanks for ideas

Javascript Fetch API and MYSQL

My purpose is to select data from MYSQL database using Javascript Fetch API. I can do it using AJAX as follows:

File ‘getUser.php’:

<?php
$con = mysqli_connect('hostname','username','password','database');
$q = intval($_POST['q']);
if ($con) {
  $sql = "SELECT * FROM user WHERE id = '".$q."'";
  $result = mysqli_query($con, $sql);
  $row = mysqli_fetch_array($result)
  if ($row) {
      echo "$row[1]";
  }
}
?>

File ‘index.php’:

<script>
function showUser(str) {
  let xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      ... = this.responseText;
    }
  };
  xmlhttp.open("POST", "getUser.php");
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("q="+str);
}
</script>

With Fetch API I tried this:

<script>
let file = "getUser.php";
fetch (file)
  .then(x => x.text())
  .then(y => ... = y);
</script>

But I cannot find how can I pass the value of ‘str’ to file ‘getUser.php’ so as to extract from the database the data for the specific person.

Laravel and Redmine Database // query builder with eloquent

I’m new in Laravel (5.4). I work on redmine database and I want to have users role. The tables are :

users : id, login, hashed_password,...
members : id, user_id, project_id, created_on, mail_notification
member_roles : id, member_id (foreign key), role_id, inherited_from
roles : id, name,...

My query works perfectly but I want to make it fluent without “->select(…)” :

$membersRole = DB::connection('redmine')
      ->select('SELECT roles.name  as role, user_id
        FROM users, members, projects, member_roles, roles
        WHERE projects.id = ?
                  AND members.user_id = ?
                  AND members.project_id = projects.id
                  AND members.id = member_roles.member_id
                  AND roles.id = member_roles.role_id
        LIMIT 1', [$id, $userId]);

How can I do it ?

remove duplicates from array of objects array

how do I remove duplicate from below JSON
checking website_name and only keeping num_followers with greatest value per date

the output should be just one value of website name in each websites array for each date

[
    {
        "date": "2022-02-15",
        "websites": [
            {
                "website_name": "instagram",
                "num_followers": "123146780"
            },
            {
                "website_name": "instagram",
                "num_followers": "123134954"
            },
            {
                "website_name": "tiktok",
                "num_followers": "123184229"
            }
        ]
    },
    {
        "date": "2022-02-14",
        "websites": [
            {
                "website_name": "instagram",
                "num_followers": "123057832"
            },
            {
                "website_name": "tiktok",
                "num_followers": "123058141"
            },
            {
                "website_name": "tiktok",
                "num_followers": "123058219"
            },
            {
                "website_name": "instagram",
                "num_followers": "123059280"
            }
        ]
    }
]

Undefined variable: name Laravel

I am trying to make an edit form but when I fire the editData Function it Gives me the error
which is ‘Undefined variable: name‘.I tried so Hard to Find the solution but nothing works
Maybe I’m missing something which I don’t know. I Need Help to Move Forward.

Here is my code:-

ProductControlller.php

<?php

namespace AppHttpControllers;

use AppProduct;
use IlluminateHttpRequest;
use IlluminateSupportFacadesDB;
class ProductController extends Controller
{
    
    public function InsertForm()
    {
    return view('prodInsert');
    }


    
    public function Prodcreate(Request $request)
    {
        $pName=$request->input('pname');
        $pPrice=$request->input('pprice');
        $pDesc=$request->input('pdesc');
        $pQuantity=$request->input('pquantity');

            $data=array('pname' =>$pName,'pprice' =>$pPrice,'pdesc' =>$pDesc,'pquantity' =>$pQuantity);
        DB::table('products')->insert($data);
        echo "Record Inserted Succefully<br>";
        echo "<a href='/Display'>Display Data</a><br>";
        echo "<a href='/prodInsert'>Add Product</a>";


    }

 
    public function selectData(Request $request)
    {
        $tabledata=DB::select('select * from products');
        return view('Display',['tabledata'=>$tabledata]);
       }

    public function deleteData(Request $request,$id){
        DB::table('products')->delete($id);
        return redirect('Display');

        }
      public function show($id)
        {
            $tabledata=DB::select('select * from products where id = ?',[$id]);
            return view('editform',['tabledata'=>$tabledata]);
        }

 
    public function editData(Request $request,$id)
    {
         $pName=$request->input('name');
        $pPrice=$request->input('price');
        $pDesc=$request->input('desc');
        $pQuantity=$request->input('quantity');

         DB::update('update products set pName=?','pPrice=?','pDesc=?','pQuantity=?',[$name,$price,$desc,$quantity,$id]);


   
    }
   

}

And this is my EditForm.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>PROD INSERT</title>
</head>
<body>

    <form action="/edit/<?php echo $tabledata[0]->id; ?>">

    @csrf
    <h4 align="center"><a href="Display"> Click here</a> Edit</h4>

    <table align="center">
        <tr>
            <td>Product name</td>
            <td><input type="text" name="name" value="<?php echo$tableData[0]->product_name; ?>"></td>
        </tr>
        <tr>
            <td>Product Price</td>
            <td><input type="text" name="price"></td>
        </tr>
        <tr>
            <td>Product Description</td>
            <td><input type="text" name="desc"></td>
        </tr>
        <tr>
            <td>Product Quantity</td>
            <td><input type="text" name="quantity"></td>
            <br>
        </tr>

            <td><input type="submit" name="submit"></td>

        
    </table>
</form>


</body>
</html>

I can provide more code if needed.
Thanks for Your Support 🙂

Multi auth with laravel sanctum

I am building a home service application with laravel for backend and react for frontend. So I use laravel sanctum for session-based authentication. In the future, I will probably need mobile application too. So, sanctum is the best choice possible.

I have two types of users. user and worker. They are in separate tables in database and I want to use multiple guards to separately authenticate them.

I have used the answer in this link and it does not work.
In my auth.php config file, I use these guards and providers:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'user' => [
            'driver' => 'sanctum',
            'provider' => 'users',
        ],
        'worker' => [
            'driver' => 'sanctum',
            'provider' => 'workers',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => AppModelsUser::class,
        ],
        'workers' => [
            'driver' => 'eloquent',
            'model' => AppModelsWorker::class,
        ],
    ],

But when I try to log in user in my controller:

auth('user')->login($user);

It gives me the following error:

"message": "Method Illuminate\Auth\RequestGuard::login does not exist.",

Actually, I tried to use default sanctum guard for user and log user in using ‘web’ guard:

auth('web')->login($user);

and It works, But an authenticated user can have access to the routes that need worker authentication:

    Route::prefix('worker')->name('worker.')->middleware(['auth:worker'])->group(function () {
         // ...
    });

So what should I do?

Retrieve sessionStorage variable mid way through a multi-step popup form

I would like to retrieve the value of a sessionStorage variable that was set in step 1 of a multi-step pop up to help in the conditional display of text in step 3. All five steps sit within a form and every post is handled by AJAX routines and are working fine.

Does anyone have any ideas about how I can pass the variable (selectedRole) back through to the front end from AJAX so I can use it in step 3?

My code to save the variable is as follows:-

    function setUpPopupRegistrationForm() {
        
        $('.js-popup-register-button').on('click', function() {
           
            let storage = window.sessionStorage;
            let selectedRole = this.dataset.role;
            
            storage.clear('selectedRole');
            storage.setItem('selectedRole', selectedRole);
            
            navigateToNextStep(this);
            
        });
        
    }
<div class="form__step js-popup-register-step" data-step="1">
  <h3>
    <?php the_field('title_1', 'option'); ?>
  </h3>
  <div class="d-flex flex-column flex-sm-row justify-content-between">
    <div class="button button--blue js-popup-register-button" data-role="member"> <span>Member</span>
    </div>
    <div class="button js-popup-register-button" data-role="guest"><span>Guest</span></div>
  </div>
</div>

ErrorException require(/vendor/magento/framework/registration.php): failed to open stream: No such file or directory in magento 2.3.7

i have two Magento projects,

website1 with :
-Magento version 2.3.1
-php fpm7.1
-mysql 5.7
-apache2 2.4.41
-composer 1
-in the file /etc/apache2/sites-available/website1.app.local.fr.conf

<VirtualHost *:80>
    ServerName website1.app.local.fr
    ServerAlias bo.website1.app.local.fr
    DocumentRoot "/var/www/html/website1/web"

    # Sources
    <Directory "/var/www/html/ecom-web/web">
        Options Indexes FollowSymLinks MultiViews Includes
        AllowOverride all
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>
    
    <FilesMatch .php$>
    SetHandler "proxy:unix:/run/php/php7.1-fpm.sock|fcgi://localhost"
    </FilesMatch>

    # Logs
        ErrorLog "/var/log/apache2/website1.error_log"
        CustomLog "/var/log/apache2/website1.access_log" common
</VirtualHost>

# SSL
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName website1-web.app.local.fr
        ServerAlias bo.website1-web.app.local.fr
        DocumentRoot "/var/www/html/website1/web"

    # SSL
    SSLEngine on
    SSLCertificateFile "/var/www/html/website1/ssl/website1.app.local.fr.crt"
    SSLCertificateKeyFile "/var/www/html/website1/ssl/website1.app.local.fr.key"

        # Sources
        <Directory "/var/www/html/website1/web">
            Options Indexes FollowSymLinks MultiViews Includes
            AllowOverride all
            Order allow,deny
            Allow from all
            Require all granted
        </Directory>
        
        <FilesMatch .php$>
    SetHandler "proxy:unix:/run/php/php7.1-fpm.sock|fcgi://localhost"
    </FilesMatch>

        # Logs
        ErrorLog "/var/log/apache2/website1.error_log"
        CustomLog "/var/log/apache2/website1.access_log" common
    </VirtualHost>
</IfModule>

and wibsite2 with :
-Magento version 2.3.7
-php fpm7.4
-mysql 5.7
-apache2 2.4.41
-composer 2
-in the file /etc/apache2/sites-available/website2.app.local.fr.conf

<VirtualHost *:80>
    ServerName website2.app.local.fr
    ServerAlias bo.website2.app.local.fr
    DocumentRoot "/var/www/html/website2/web"

    # Alias
    Alias "/media" "/var/www/html/website2/web/pub/media"

    # Sources
    <Directory "/var/www/html/website2/web">
        Options Indexes FollowSymLinks MultiViews Includes
        AllowOverride all
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>
    
    <FilesMatch .php$>
      SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost"
    </FilesMatch>

    # Logs
        ErrorLog "/var/log/apache2/website2.error_log"
        CustomLog "/var/log/apache2/website2.access_log" common
</VirtualHost>

# SSL
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName website2.app.local.fr
        ServerAlias bo.website2.app.local.fr
        DocumentRoot "/var/www/html/website2/web"

        # SSL
        SSLEngine on
        SSLCertificateFile "/var/www/html/website2/ssl/website2.app.local.fr.crt"
        SSLCertificateKeyFile "/var/www/html/website2/ssl/website2.app.local.fr.key"

        # Alias
        Alias "/media" "/var/www/html/website2/web/pub/media"

        # Sources
        <Directory "/var/www/html/website2/web">
            Options Indexes FollowSymLinks MultiViews Includes
            AllowOverride all
            Order allow,deny
            Allow from all
            Require all granted
        </Directory>
        
        <FilesMatch .php$>
       SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost"
    </FilesMatch>

        # Logs
        ErrorLog "/var/log/apache2/website2.error_log"
        CustomLog "/var/log/apache2/website2.access_log" common
    </VirtualHost>
</IfModule>

i have following this tuto https://www.digitalocean.com/community/tutorials/how-to-run-multiple-php-versions-on-one-server-using-apache-and-php-fpm-on-ubuntu-18-04-fr#etape-4-test-des-deux-sites-web

the problem now is that i can run website1 perfectly with no problem with setup:upgrade,composer install… and i can access to the website by the browser, but the website2 can’t be accessible by browser, and it tells me the error below when I run composer install

 [ErrorException]                                                                                                                   
  require(vendor/magento/framework/registration.php): failed to open stream: No such file or directory  

any help please?