Missing illegal Collation issues after upgrading mysql5.7 to mysql8.0.3*

SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (utf8mb3_general_ci,IMPLICIT) and (utf8mb4_0900_ai_ci,COERCIBLE) for operation '=', query was: SELECT mobile_users.* FROM mobile_users WHERE (first_name = 'John') AND (last_name = 'Rodríguez')

Getting above error when running a select query in php, Last_name is having special character so this issue occurs. but this was working fine in mysql5.7 and now after upgrade to mysql8.0 getting above exception.

How to fix this one without modifying existing production data’s in db. My DB structure is (SaaS) Client based dbs. So have many db’s which is created using mysql5.7.

Experience with Open AI`s Assistant API and saved messages in Database

It is possible to migrate from database driven chat/completion behavior to assistants api methods. I will not lost my data from conversation und also I will use the optimization functions from assistants api.

I use open AI php client in Laravel for the beta assistants api. Currently I have this solution:

    $messages = Message::where(user_id, Auth::id())->orderBy('created_at', 'asc') -> select(['role', 'content']);
    $chatMessages = $messages->map(function ($item) {
            return ['role' => $item->role, 'content' => $item->content];
        });
    $chat_instruction = 'this is a super bot';
    $message_instruction = ['role' => 'assistant', 'content' => $chat_instruction];
        $chatMessages->prepend($message_instruction);
    $response = $client->chat()->create([
            'model' => 'gpt-4-1106-preview',
            'messages' => $chatMessages,
            'temperature' => 0,
            'tools' => $tools,
        ]);

Store HTML and dynamic PHP variables in MySQL table

I am currently able to save html in to a MySQL database and call that information when needed and all renders correctly.

However now i want to add dynmaic PHP variables also to the MySQL table along with the html, but when called from the database it displays as html/text and the PHP variables are no longer dynamic. Is this possible?

How can i store html and PHP variables, so they can be returned in the same way.

Please see my example, $ProfileName, $ProfileAge, $ProfileGender are my dynamic variables:

<div class="sampleheader">
    <div class="headerimage"><img src="/images/sample.jpg" /></div>
    <div class="headerprofilename">'.$ProfileName.'</div>
    <div class="headerprofileage">'.$ProfileAge.'</div>
    <div class="headerprofilegender">'.$ProfileGender.'</div>
</div>

Maybe I should return all as html and then use regex or str_replace to find (‘.$ProfileName.’, ‘.$ProfileAge.’, ‘.$ProfileGender.’) and somehome replace for the actual variables.

Any help is much appricated, thanks

Website ranking ids down due to change in sever and upgrade database from php version 5 to 8 [closed]

My website was hacked on October 24th, and unfortunately, it was hacked again on October 27th. In response to these security breaches, I changed the server IP and upgraded the PHP version from 5.6 to 8.1.

Despite taking these measures, I have observed a decline in my website’s ranking after the server change. When the website was initially hacked, I added a no-index tag to prevent negative effects on rankings. Ideally, the ranking should not have been affected. However, the decline occurred after the server changes.

I would appreciate your insights on whether the hacking or the server change has had the most significant impact on my ranking.

Trouble Retrieving X-Robots-Tag Added via .htaccess in Magento 2

For specific SEO requirements, I have added an X-Robots-Tag HTTP header via the .htaccess file on my server. However, I am facing an issue: I am unable to retrieve or read this header within Magento 2.

Here are the steps I have taken:

  1. Added the X-Robots-Tag header in the .htaccess file.
  2. Confirmed that the header is correctly set (visible through browser developer tools).
  3. Attempted to access this header in Magento 2. (getallheaders, getHeaders (with response class), $_SERVER …)

I am looking for advice or solutions on how to access the X-Robots-Tag header from within Magento 2. Is there a specific configuration required in Magento 2 or on the server to make this header accessible?

Thanks !

Anyone knows the client? [closed]

Hey we are having some problems with our website and yes I know waht the Error Code 404 stands for but I am more confused about the client that is putting it out does anyone of you maybe know to which client this belongs?

I was already in the directories for it and just saying in the URL to open the index.php in the wanted directory works perfectly like it should but some of our sides don’t really have an index.php so we can’t open them even tho we were able to do that on localhost

Error Code

PHP errors not showing in Chrome network tab (but show in Firefox)

The Google Chrome network tab doesn’t seem to display PHP errors properly.
Firefox and Insomnia perfectly show all errors, but chrome just shows

Failed to load response data: No data found for resource with given
identifier

chrome display error

I’ve tried setting the headers 'Content-Type: application/json; charset=utf-8' and a lot of other stuff but nothing seems to work.

Code throwing the error:

dd('Test'); // With symfony/var-dumper package
// OR
throw new Exception('Test');

My error handler:

    $payload = [
        'error' => [
            'message' => $exception->getMessage(),
            'code' => $exception->getCode()
        ]
    ];

    $response->getBody()->write(json_encode($payload));

    return $response->withHeader('Content-Type', 'application/json')
        ->withStatus(500);

Any ideas how I can do this? I’m using plain PHP, with Laravel and Symfony this is no problem at all.

Response is handled incorrectly in ajax [duplicate]

I have a handler and I have jQuery, which uses ajax to get data from the database and which then needs to be parsed and added to a new array for the FullCalendar calendar. The trouble is that response contains data, but it doesn’t want to push them into an array in any way, all strings are undefined.

So, my handler:

$bookings = array();
  foreach ($results as $row) {
    $bookingDateTime = $row['booking_datetime'];
      $bookings[] = array(
          'name' => $row['name'],
          'start' => date('Y-m-d', strtotime($bookingDateTime)),
      );
  }

echo json_encode($bookings);
$.ajax({
  url: ajaxurl,
  type: 'POST',
  data: {
    action: 'get_bookings',
  },
  success: function (response) {
   var events = [];
   for (var i = 0; i < response.length; i++) {
     events.push({
       title: response[i].name,
       start: response[i].start,
     });
   }
   successCallback(events);
   } .....

The response contains:

[{"name":"luk","start":"2023-11-10"}]

But events is empty, more precisely {name:"undefined",start:"undefined"}

And what is unclear to me, the entry in response 1, and in events for pushes several.

I will be grateful for any hint. Thanks)

What is the cause of this URL error in PHP? I believe the error originates from infoconn

The requested URL was not found on this server.
I have a table in the database titled persondetails

personcreate.php

<?php
session_start();
?>

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
  </head>
  <body>
    
    <div class="container">
        
        <?php include('message.php'); ?>
        <div class="row">
            <div class="col-md-12">
                <div class="class">
                    <div class="class-header">
                        <h3> Add Info
                            <a href="index.php" class="btn btn-danger float-end">Back</a>
                        </h3>
                    </div>
                    <div class="card-body">
                        <form action="infoconn" method="POST">
                             <div class="mb-3">
                                <label>First name</label>
                                <input type="text" firstname="firstname" class="form-control">
                             </div>
                             <div class="mb-3">
                                <label>Last name</label>
                                <input type="text" lastname="lastname" class="form-control">
                             </div>
                             <div class="mb-3">
                                <label>Date Registered</label>
                                <input type="date" datereg="datereg" class="form-control">
                             </div>
                             <div class="mb-3">
                                <label>Address</label>
                                <input type="text" address="address"  class="form-control">
                             </div>
                             <div class="mb-3">
                                <label>Phone</label>
                                <input type="text" phone="phone" class="form-control">
                             </div>
                             <div class="mb-3">
                                <label>Email</label>
                                <input type="email" email="email" class="form-control">
                             </div>
                             <div class="mb-3">
                                <button type="submit" name="save_info" class="btn btn-primary">Save Info</button>
                             </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
  </body>
</html>

infoconn.php

<?php
session_start();
require 'dbconn.php';

if(isset($_POST['save_info'])) {
    $firstname = mysqli_real_escape_string($con, $_POST['firstname']);
    $lastname = mysqli_real_escape_string($con, $_POST['lastname']);
    $datereg = mysqli_real_escape_string($con, $_POST['datereg']);
    $address = mysqli_real_escape_string($con, $_POST['address']);
    $phone = mysqli_real_escape_string($con, $_POST['phone']);
    $email = mysqli_real_escape_string($con, $_POST['email']);

    $query = "INSERT INTO persondetails (firstname,lastname,datereg,address,phone,email) VALUES 
        ('$firstname', '$lastname', '$datereg', '$address', '$phone', '$email')";

    $query_run = mysqli_query($con, $query);
    if($query_run) {
        $_SESSION['message'] = "Info Added";
        header("Location: personcreate.php");
        exit(0);
    }
    else {
        $_SESSION['message'] = "Failed to Add";
        header("Location: personcreate.php");
        exit(0);
    }
}


?>

message.php

<?php
    if(isset($_SESSION['message'])) :
?>

<div class="alert alert-warning alert-dismissible fade show" role="alert">
        <strong>Holy guacamole!</strong> Success! <?= $_SESSION['message'] ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php
    unset($_SESSION['message']);
endif;
?>`

dbconn.php

`<?php
$con = mysqli_connect("localhost","root","","exam_torres");

if(!$con) {
    die('Connection Error'. mysqli_connect_error());
}

?>

I have tried looking at other posts with the same problem, but all the suggested answers and solutions proved to be unfruitful. I was able to enter the personcreate.php, but when I clicked the button, the url error appeared. Perhaps accessing the database part is the error? But I can’t see where the error lies.

PHP Webdriver Chrome not starting and loading for very long time

I have installed php-webdriver/webdriver version “1.7.*” through composer and trying to start chrome driver on amazon ec2 server.

use FacebookWebDriverChromeChromeDriver;
use FacebookWebDriverChromeChromeOptions;
use FacebookWebDriverRemoteDesiredCapabilities;

putenv('webdriver.chrome.driver=/path/to/chromedriver')

$desiredCapabilities = DesiredCapabilities::chrome();
$desiredCapabilities->setCapability('acceptSslCerts', false); //Disable accepting SSL certificates
$userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36';
$chromeOptions = new ChromeOptions();
$chromeOptions->addArguments(
    array_merge([
        '--headless',
        '--disable-gpu',
        '--no-sandbox',
        'user-agent=' . $userAgent,
    ], $headers));
$desiredCapabilities->setCapability(ChromeOptions::CAPABILITY, $chromeOptions);
echo "reachedn";
$driver = ChromeDriver::start($desiredCapabilities);
$driver->get('https://www.example.com');
sleep(5);
$currentURL = $driver->getCurrentURL();
echo $currentURL;

When I am running from command line its loading and working fine.

php index.php

But when I am trying to run this same file through command line internally, let’s say there is a api file api.php at base endpoint https://api.example.com and I am hitting https://api.example.com/api.php

$result = shell_exec("cd path/to/root-of-site/; php index.php");
echo $result;

Its reaching till the code echo "reachedn"; but not starting the chrome driver at all.

Really appreciate the solution and it will help other people who literally have not idea what’s happening here.

Serialization of ‘SymfonyComponentHttpFoundationFileUploadedFile’ is not allowed when import excel in laravel

I try to import data from excel to my database with maatwebsite, in local network it work but when i try that after hosting my project in cpnel its get error like below

enter image description here

can someoen help me with that issues?

this is my code to import excel data to database

enter image description here

enter image description here

i have tryed this way but it didnt work

Laravel excel import could not find zip error

Optimizing and Accelerating File Upload Speed to Google Drive in PHP – Laravel

I’m using Google Drive to upload images, videos, etc. However, I find its performance quite slow, even though I’ve implemented chunking. Is there any optimization method to boost the upload speed? Or are there any CDNs similar to Google Drive but with faster speeds? Please help me address this issue. Thank you :<

 public static function uploadFile($file)
{
    $client = self::getClient();
    $driveService = new Google_Service_Drive($client);

    // Check if 'social' folder exists
    $socialFolderId = self::checkFolderExists($driveService, 'social');

    // If 'social' folder doesn't exist, create it
    if (!$socialFolderId) {
        $folderMetadata = new Google_Service_Drive_DriveFile([
            'name' => 'social',
            'mimeType' => 'application/vnd.google-apps.folder',
        ]);
        $createdFolder = $driveService->files->create($folderMetadata, [
            'fields' => 'id',
        ]);
        $socialFolderId = $createdFolder->id;
    }

    // Create a folder name based on the date
    $dateFolderName = date('d-m-Y');
    $dateFolderExists = self::checkFolderExists($driveService, $dateFolderName);

    // If the date folder doesn't exist, create it in the 'social' folder
    if (!$dateFolderExists) {
        $folderMetadata = new Google_Service_Drive_DriveFile([
            'name' => $dateFolderName,
            'parents' => [$socialFolderId],
            'mimeType' => 'application/vnd.google-apps.folder',
        ]);
        $createdFolder = $driveService->files->create($folderMetadata, [
            'fields' => 'id',
        ]);
        $folderId = $createdFolder->id;
    } else {
        // If the date folder exists, use its id
        $folderId = $dateFolderExists;
    }

    // Generate a new file name
    $newFileName = bin2hex(random_bytes(16)) . '.' . $file->getClientOriginalExtension();

    // Define allowed extensions
    $allowedExtensions = ['png', 'jpg', 'exe', 'vtt', 'mp4', 'txt', 'zip', 'rar', 'docx', 'pdf', 'msi'];
    $fileExtension = $file->getClientOriginalExtension();

    if (in_array($fileExtension, $allowedExtensions)) {
        // Define the chunk size
        $chunkSizeBytes = 10 * 1024 * 1024; // 1MB

        // Call the API with the media upload, defer so it doesn't immediately return.
        $client->setDefer(true);

        // File metadata
        $fileMetadata = new Google_Service_Drive_DriveFile([
            'name' => $newFileName,
            'parents' => [$folderId],
        ]);

        // Create a request
        $request = $driveService->files->create($fileMetadata);

        // Create a media file upload to represent our upload process.
        $media = new Google_Http_MediaFileUpload(
            $client,
            $request,
            'application/octet-stream',
            null,
            true,
            $chunkSizeBytes
        );

        // Set file size
        $media->setFileSize(filesize($file->getRealPath()));

        // Upload the various chunks.
        // The status will be false until the process is complete.
        $status = false;

        // Open file handle
        $handle = fopen($file->getRealPath(), "rb");
        $totalFileSize = filesize($file->getRealPath());
        $uploadedSize = 0;

        while (!$status && !feof($handle)) {
            // Read a chunk of file
            $chunk = fread($handle, $chunkSizeBytes);

            // Upload the chunk
            $status = $media->nextChunk($chunk);
            $uploadedSize += strlen($chunk);

            // Calculate the progress based on the uploaded size
            $progress = ($uploadedSize / $totalFileSize) * 100;

            // Send an event with the current progress
            event(new FileUploadProgressEvent($progress));
        }

        // Ensure the final progress is sent, even if it doesn't reach 100%
        if ($progress < 100) {
            event(new FileUploadProgressEvent(100));
        }

        // Close file handle
        fclose($handle);

        // Reset to the client to execute requests immediately in the future.
        $client->setDefer(false);
        // Create permissions for the file
        $permissionMetadata = new Google_Service_Drive_Permission([
            'type' => 'anyone',
            'role' => 'reader',
        ]);

        // Add permissions to the file
        $driveService->permissions->create($status->id, $permissionMetadata);

        // Get file metadata
        $uploadedFile = $driveService->files->get($status->id, ['fields' => 'webViewLink']);
        $downloadLink = "https://drive.google.com/uc?export=download&id=" . $status->id;
        // return ['downloadLink' => $downloadLink, 'webViewLink' => $uploadedFile->webViewLink, 'id' => $status->id];
        return response()->json([
            'success' => true,
            'message' => 'File uploaded successfully!',
            'filename' => $newFileName,
            'filepath' => $downloadLink,
            'fileId' => $status->id
        ]);

    } else {
        return false;
    }
}

Sorting a 12 digit array of strings in PHP numerically

I have some PHP code which is doing a sort for me on my array of numbers. The numbers in particular (for example) are as followed:

040613002625″,
040613000277″,
040613000511″,
040613001685″,
040613003275″, etc

When I sort my values however, 002625 is appearing before 001685 which is incorrect.

Note that I am using pagination on my page. I have 190 pages with listings of 30 items per page. The pagination could very well be the reason behind the issue as it’s not sorting all 5,000 listings and instead it’s only reading the first 30 and doing a sort on that single page. It’s also incredibly slow to read and render the page (upwards of 1 minute).

Here is a snippet of my existing code showing the sort logic. Does it look correct?

$per_page = 30;
$current_page = $this->get_pagenum();
$a = $this->users_data;
$this->users_data = array_slice($a, (($current_page - 1) * $per_page), $per_page);

// call the sorting function
usort($this->users_data, array(&$this, 'usort_reorder'));

// sorting function
function usort_reorder($a, $b)
{
    // if no sort, default to user_login
    $orderby = (!empty($_GET['orderby'])) ? $_GET['orderby'] : 'ID';

    // if no order, default to asc
    $order = (!empty($_GET['order'])) ? $_GET['order'] : 'asc';

    // determine sort order
    $result = strcmp($a[$orderby], $b[$orderby]);
    
    // send final sort direction to usort
    return ($order === 'asc') ? $result : -$result;
}

Thanks.

Arranging the elements of the array, Properly sorting the data

I have a problem with arranging the correct items.

It receives data from the database $data[‘c_list]:

array(3) { [0]=> object(stdClass)#14 (3) { ["c_id"]=> int(1) ["company_name"]=> string(13) "Firma 1" ["name"]=> string(14) "adres główny" } [1]=> object(stdClass)#15 (3) { ["c_id"]=> int(1) ["company_name"]=> string(13) "Firma 1" ["name"]=> string(15) "adres dodatkowy" } [2]=> object(stdClass)#16 (3) { ["c_id"]=> int(3) ["company_name"]=> string(14) "Firma 2" ["name"]=> string(14) "adres główny" } } 

and
$data[‘a_list’]:

array(3) { [0]=> object(stdClass)#13 (3) { ["c_a_id"]=> int(1) ["c_id"]=> int(1) ["name"]=> string(14) "adres główny" } [1]=> object(stdClass)#18 (3) { ["c_a_id"]=> int(3) ["c_id"]=> int(1) ["name"]=> string(15) "adres dodatkowy" } [2]=> object(stdClass)#19 (3) { ["c_a_id"]=> int(4) ["c_id"]=> int(3) ["name"]=> string(14) "adres główny" } } 

And now I would like to get this result:
Firma 1
–> adres główny
–> adres dodatkowy
Firma 2
–> adres główny

here is my code:

    foreach ($data['c_list'] as $c => $key) {
        echo $key->company_name . '<br>';
        foreach ($data['a_list'] as $a)
        if($key->c_id == $a->c_id) {
             echo $a->name . '<br>';
         }
    }

Unfortunately, what I “produced” duplicates the first company twice:

Result:

Firma 1

adres główny

adres dodatkowy

Firma 1

adres główny

adres dodatkowy

Firma 2

adres główny

Please help me. Thank you.

Use php variable as src attribute in an HTML image

I’m coding a cart page that checks if there’s something in the cart and then, if the condition is true,, it echoes a div with a picture of the product, the amount, the price and the name of the product. The variables are inside a session array because I take the data from other pages (login and sign in) where I declare the following array:

$myProdArray=[
  array("Superbiomin", 0.016, 3, "/img/superbiomin.jpg"), //name, units, price, image
  array("Prop P Jaleia Reial", 0.010, 2, "/img/proppjalea.jpg"),
  array("Vitamina C 500mg Mastegable Solaray", 0.0097, 1, "/img/vitc.jpg"),
];
$_SESSION['prods'] = $myProdArray;

Everything works but I don’t know how to refer to the image name string stored in the session array. Here’s the body code of the cart page:

<body class="cartbody">
<?php
  $nothing = true;
  for($i = 0; $i<3;$i++){
    if($_SESSION['prods'][$i][2] !== 0) {
      $nothing = false;
      if($nothing == false) {   
    ?>
      <div class="cartbodyfalse">
        <div class="productSummary">
        <?php
          for($j=$i; $j<3;$j++){
            if($_SESSION['prods'][$j][2]>0)echo "
              <div class='indivProdRow'><img src=".
               $_SESSION['prods'][$j][2]." class='prodcartimg'><h5>x" . 
               $_SESSION['prods'][$j][2] . " " . 
               $_SESSION['prods'][$j][0] ." " . 
               $_SESSION['prods'][$j][1] ." ETH</h5></div>";
             }
           }
           echo "</div>";
           $i = $j;       
          }   
        }
        if($nothing == true){
            echo "<div class='cartbodytrue'><div class='cartmsg'><h4 class='nothing'>Sembla que encara no tens res al carret</h4><a href='botiga.php'><button class='btn kbuyin'><i class='fa-solid fa-shop'></i> Seguir comprant</button></a></div></div>";
        } else { ?>
          <div class="ticketactions">
          <?php ?>
          </div>
        <?php } ?> 
        </div>     
    </body>

I was expecting the code to output the image, however, it outputs the mini img logo as the src attribute value is incorrect. Finally, apart from the code previously showed, I tried using “.{‘session array’}.”, and “.’session array'”.