React js POST method to two or more tables [closed]

0

I’m a newbie to react and have been trying to learn it by a random car project with crud operations. I got it working and all.. but now i want to add an option of asigning it to a person which probably would be a separate table with some data.

I’m also pretty new to PHP so i can’t wrap my mind around this problem 😀 I have a page where i display all the cars and also have a page where i display a single car with some info and posibility to “reserve” a car. Now i would like to reserve the car but with additional info like person that reserved it. So i would have to create a user when reserving. i’m not sure how to have two “POST” methods in the same file and reference one or another depending on if i’m registering a new car or registering a new user linked to the car. I’m using tanstack and axios if it helps in any way.. probably not 😀

I’m so sorry if i’m making no sense.. i haven’t programmed in a year so i’m trying to refresh some concepts.
This is my PHP File:

I tried using LEFT JOIN but and i got some info but im not sure how id be able to post into a table depending on which form i’m submiting.
I’ve seen some answers on here but mostly there are inserting in two different tables at the same time but i don’t need to insert into the second table if i’m only trying to register a car. But on more detailes page i would need to update two tables at the same time. I don’t understand how to proceed

error_reporting(E_ALL);
ini_set('display_errors',1);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");

include 'DbConnect.php';
$objDb = new DbConnect;
$conn = $objDb -> connect ();

$method = $_SERVER['REQUEST_METHOD'];
switch ($method){

    case 'GET':
        $sql = "SELECT * FROM coches";
        $path = explode('/', $_SERVER['REQUEST_URI']);
      if(isset($path[3]) && is_numeric($path[3])){
        $sql .= " WHERE id = :id";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':id', $path[3]);
        $stmt->execute();
        $coches = $stmt->fetch(PDO::FETCH_ASSOC);

      }else{
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        $coches = $stmt->fetchAll(PDO::FETCH_ASSOC);
      }

      echo json_encode($coches);
      break;

    case 'POST':
        $coche = json_decode( file_get_contents('php://input'));
        $sql = "INSERT INTO coches(id,imagen,condicion,puertas,cv,km,marca,modelo,precio,color,detalles,anio,created_at) VALUES (null, :imagen, :condicion,:puertas,:cv,:km, :marca, :modelo, :precio, :color,:detalles,:anio, :created_at)";
        $stmt= $conn->prepare($sql);
        $created_at = date('Y-m-d');
        $stmt->bindParam(':imagen',$coche->imagen);
        $stmt->bindParam(':condicion',$coche->condicion);
        $stmt->bindParam(':puertas',$coche->puertas);
        $stmt->bindParam(':km',$coche->km);
        $stmt->bindParam(':cv',$coche->cv);
        $stmt->bindParam(':marca',$coche->marca);
        $stmt->bindParam(':modelo',$coche->modelo);
        $stmt->bindParam(':precio',$coche->precio);
        $stmt->bindParam(':color',$coche->color);
        $stmt->bindParam(':detalles',$coche->detalles);
        $stmt->bindParam(':anio',$coche->anio);
        $stmt->bindParam(':created_at',$coche->created_at);
        if($stmt -> execute()){
            $response = ['status' => 1, 'message' => 'El coche se ha registrado correctamente'];
        }
        else{
            $response = ['status' => 0, 'message' => 'No se ha registrado'];
        }
        echo json_encode($response);
        break;

    case "PUT":
        $coche = json_decode( file_get_contents('php://input') );
        $sql = "UPDATE coches SET condicion= :condicion,puertas= :puertas,km= :km,cv= :cv,marca= :marca, modelo =:modelo, precio =:precio, color=:color,detalles=:detalles,anio=:anio, updated_at =:updated_at WHERE id = :id";
        $stmt = $conn->prepare($sql);
        $updated_at = date('Y-m-d');
        $stmt->bindParam(':id', $coche->id);
        $stmt->bindParam(':marca', $coche->marca);
        $stmt->bindParam(':modelo', $coche->modelo);
        $stmt->bindParam(':cv', $coche->cv);
        $stmt->bindParam(':km', $coche->km);
        $stmt->bindParam(':puertas', $coche->puertas);
        $stmt->bindParam(':condicion', $coche->condicion);
        $stmt->bindParam(':precio', $coche->precio);
        $stmt->bindParam(':color', $coche->color);
        $stmt->bindParam(':detalles', $coche->detalles);
        $stmt->bindParam(':anio', $coche->anio);
        $stmt->bindParam(':updated_at', $updated_at);

        if($stmt->execute()) {
            $response = ['status' => 1, 'message' => 'Los datos del coche ha sido actualizado.'];
        } else {
            $response = ['status' => 0, 'message' => 'Los datos no se han actualizado'];
        }
        echo json_encode($response);
        break;
    
    case "DELETE":
        $sql = "DELETE FROM coches WHERE id= :id";
        $path = explode('/', $_SERVER['REQUEST_URI']);
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':id', $path[3]);
        $stmt->execute();
        break;
}

Why the php-actions/composer action fails despite having installed pdo_mysql

I have this actions that allows me to run unit tests upon PR:

name: on-pr-unittest

on:
  pull_request:
    branches:
      - dev

jobs:
  run_unit_test:
    runs-on: ubuntu-latest
    services:
      mariadb:
        image: mariadb:latest
        ports:
          - 33306:3306
        env:
          MYSQL_USER: php_usr
          MYSQL_PASSWORD: php_apsswd
          MYSQL_DATABASE: test_php_app
          MYSQL_ROOT_PASSWORD: password

    steps:
      - name: Check Out Repo
        uses: actions/checkout@v4

      - name: Remove Default Mysql and install nessesary tools to ping db connection
        env:
          DEBIAN_FRONTEND: noninteractive
        run: |
          sudo service mysql stop
          sudo apt-get update && sudo apt-get purge -y mysql* && sudo apt-get install -y mariadb-client-10.6 netcat

      # I do not want to modify the .env.testing therefore I spin my own host
      - name: Add hosts to /etc/hosts
        run: |
          sudo echo "127.0.0.1 mariadb" | sudo tee -a /etc/hosts

      - name: Test Connect Into DB
        run: |
          docker ps &&
          nc -vz mariadb 33306 &&
          mysql -h localhost -u php_usr -pphp_apsswd test_php_app -P 33306 -e "select DATABASE();"

      - name: Setup PHP with PECL extension
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
          extensions: bcmath, ctype, curl, dom, fileinfo, filter, hash, mbstring, openssl, pcre, pdo, pdo_mysql, tokenizer, libxml

      - name: Install dependencies
        uses: php-actions/composer@v6

      - name: PHPUnit tests
        run: |
          sed -i "s/DB_PORT=.*/DB_PORT=33306/" .env.testing &&
          ./vendor/bin/phpunit

But upon ruuning the step php-actions/composer I get this error:

Run php-actions/composer@v6
Run set -e
  
Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Your lock file does not contain a compatible set of packages. Please run composer update.
  Problem 1
    - Root composer.json requires PHP extension ext-pdo_mysql * but it is missing from your system. Install or enable PHP's pdo_mysql extension.
To enable extensions, verify that they are enabled in your .ini files:
    - /usr/local/etc/php/conf.d/docker-php-ext-sodium.ini
You can also run `php --ini` in a terminal to see which files are used by PHP in CLI mode.
Alternatively, you can run Composer with `--ignore-platform-req=ext-pdo_mysql` to temporarily ignore these required extensions.
Error: Your lock file does not contain a compatible set of packages. Please run composer update.

  Problem 1
    - Root composer.json requires PHP extension ext-pdo_mysql * but it is missing from your system. Install or enable PHP's pdo_mysql extension.

To enable extensions, verify that they are enabled in your .ini files:
    - /usr/local/etc/php/conf.d/docker-php-ext-sodium.ini
You can also run `php --ini` in a terminal to see which files are used by PHP in CLI mode.
Alternatively, you can run Composer with `--ignore-platform-req=ext-pdo_mysql` to temporarily ignore these required extensions.

Despite installing the pdo_mysql extetion on a previous step:

      - name: Setup PHP with PECL extension
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.3'
          extensions: bcmath, ctype, curl, dom, fileinfo,sodium, filter, hash, mbstring, openssl, pcre, pdo, pdo_mysql, tokenizer, libxml

Why this happens and how I can fix it?

PHP 7 CURL post request over 1024 characters timing out

I’m working in a Cake PHP 2 project running PHP 7.4. I’m trying to make a POST request via CURL to a server. I’m getting some odd behaviour with CURLOPT_POSTFIELDS. I need to send my data as an encoded JSON array so I’m doing json_encode, but it seems that when checking the character count of this, anything over 1024 causes curl to timeout and not send?

I’ve checked max_input_vars which is default to 1,000, and my post_max_size is 2048M so plenty big enough, what’s going on here?

An identical problem back in 2009 is here, but trying this, no luck.

/**
 * Perform a request to store the application.
 * TODO: WIP
 */
private function storeApplication()
{
    try {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->getEndpoint());
        curl_setopt($ch, CURLOPT_POST, true);

        $customer = $this->application;

        $fields = json_encode([
            'product_type' => 'foo',
            'data_source' => 'foo',
            'data' => [
                'ApiKey' => 'foo',
                'AffId' => 'foo',
                'Application' => [
                    'SubAffId' => '',
                    'ReqRepaymentTerm' => $this->formatField($customer, 'ReqRepaymentTerm'),
                    'AppTitle' => $this->formatField($customer, 'AppTitle'),
                    'AppFirstName' => $this->formatField($customer, 'AppFirstName'),
                    'AppLastName' => $this->formatField($customer, 'AppLastName'),
                    'AppDOBDay' => $this->formatField($customer, 'AppDOBDay'),
                    'AppDOBMonth' => $this->formatField($customer, 'AppDOBMonth'),
                    'AppDOBYear' => $this->formatField($customer, 'AppDOBYear'),
                    'AppMaritalStatus' => $this->formatField($customer, 'AppMaritalStatus'),
                    'AppDependants' => $this->formatField($customer, 'AppDependants'),
                    'AppHomeStatus' => $this->formatField($customer, 'AppHomeStatus'),
                    'AppAddressYears' => $this->formatField($customer, 'AppAddressYears'),
                    'AppHouseNumber' => $this->formatField($customer, 'AppHouseNumber'),
                    'AppPostCode' => $this->formatField($customer, 'AppPostCode'),
                    'AppStreet' => $this->formatField($customer, 'AppStreet'),
                    'AppTown' => $this->formatField($customer, 'AppTown'),
                    'AppCounty' => $this->formatField($customer, 'AppCounty'),
                    'AppEmail' => $this->formatField($customer, 'AppEmail'),
                    'AppMobilePhone' => $this->formatField($customer, 'AppMobilePhone'),
                    'EmpIncomeType' => $this->formatField($customer, 'EmpIncomeType'),
                    'EmpEmployerName' => $this->formatField($customer, 'EmpEmployerName'),
                    'EmpIndustry' => 25,
                    'EmpEmployedMonths' => $this->formatField($customer, 'EmpEmployedMonths'),
                    'EmpPayFrequency' => $this->formatField($customer, 'EmpPayFrequency'),
                    'EmpNetMonthlyPay' => $this->formatField($customer, 'EmpNetMonthlyPay'),
                    'AppLoanPurpose' => $this->formatField($customer, 'AppLoanPurpose'),
                    'AppLoanPrposeOther' => '',
                    'AppHousingSpend' => $this->formatField($customer, 'AppHousingSpend'),
                    'AppCreditSpend' => $this->formatField($customer, 'AppCreditSpend'),
                    'AppUtilitiesSpend' => $this->formatField($customer, 'AppUtilitiesSpend'),
                    'AppFoodSpend' => $this->formatField($customer, 'AppFoodSpend'),
                    'AppTransportSpend' => $this->formatField($customer, 'AppTransportSpend'),
                    'AppOtherSpend' => $this->formatField($customer, 'AppOtherSpend'),
                    'BankName' => $this->formatField($customer, 'BankName'),
                    'BankSortcode' => $this->formatField($customer, 'BankSortcode'),
                    'BankAccount' => $this->formatField($customer, 'BankAccount'),
                ]
            ]
        ]);

        CakeLog::write('debug', "A: ".strlen($fields));

        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable verbose output

        $string = curl_exec($ch);
        curl_close($ch);

        $res = json_decode($string, true);

        CakeLog::write('debug', json_encode($res));

        // success
        return $res;

    } catch (Exception $e) { }

    // it never saved
    return null;
}

WhatsApp ChatBot Integeration with Wix [closed]

We manage eCommerce orders via a Wix-hosted website where order details appear on our Wix dashboard, allowing admin to assign deliveries. Now, we’ve added a WhatsApp chatbot for orders, and we need these integrated into our Wix dashboard alongside website orders. Both sources should utilize Wix API to ensure seamless data storage and management in the ‘Stores/Orders’ collection. We seek guidance on setting up backend processes, API endpoints, and testing to unify order visibility and management effectively. Any assistance or resources on this integration would be invaluable.
could you help me with this issue??

I tried with generating API keys to access with Wix API to connect with Wix Dashboard with a given endpoint in the documentation through Postman. But I am unable to connect . I am expecting it is possible to connect our whatsapp chatbot orders to that website orders in wix..

Cannot Access Storage files on c-panel for laravel 10

I am using laravel 10 and php version 8.1, i have deployed my project on c-panel , i have cloned the project successfully , i have moved my files from public to public_html and the remaining files are in my laravel directory, i have created the symlink using this command,


ln -s /home/your_cpanel_username/path/to/your/laravel/project/storage/app/public /home/your_cpanel_username/public_html/storage

the link is created successfully , but i still cannot access my storage folder,

i have checked the permissions also , the permissions are also fine, the images are bing saved into the storage/app/public/performa_invoices folder

i have tried updating the filesystems.php file in my config :

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => env('FILESYSTEM_DISK', 'local'),

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been set up for each driver as an example of the required values.
    |
    | Supported Drivers: "local", "ftp", "sftp", "s3"
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'throw' => false,
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage/app/public',
            'visibility' => 'public',
            'throw' => false,
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),
            'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
            'throw' => false,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Symbolic Links
    |--------------------------------------------------------------------------
    |
    | Here you may configure the symbolic links that will be created when the
    | `storage:link` Artisan command is executed. The array keys should be
    | the locations of the links and the values should be their targets.
    |
    */

    'links' => [
        base_path('public_html/storage') => storage_path('app/public'),
    ],

];

also changed the

FILESYSTEM_DISK=public

in my env , still cannot access, tried some other things but cannot access , i am fedup with the issue , any help regarding that will be appreciated

I’m not recieving mail from my php form, could someone take a look?

I cant seeem to get this form to work, currently it acts as though its working but not recieving any mail?

<form method="post" action="action_page.php" novalidate>
        <label for="name">Name</label>
        <input name="name" id="name" type="text" required>

        <label for="email">Email</label>
        <input name="email" id="email" type="email" required>

        <label for="message">Message</label>
        <textarea name="message" id="message" placeholder="" required></textarea>

        <div id="important">
            <label for="human">What is 2+2?</label>
            <input name="human" id="human" placeholder="">
        </div>

        <div id="contact-footer">
            <p>Your email address will only be used to reply to your message and
                your personal information
                will never be shared.</p>
        </div>

        <div id="form-flex">
            <div class="g-recaptcha-con">
                <div class="g-recaptcha" data-sitekey="6Ldkew0qAAAAAMQHlmn177hTXLtVcZ9fkmVxLqqL"></div>
            </div>
            <div class="submit-div">
                <input type="submit" id="submit" class="button" name="submit" value="Send Message">
            </div>
        </div>
    </form>
<?php
if (isset($_POST['submit'])) {
    // reCAPTCHA validation
    if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
        // Google secret API key
        $secretAPIkey = '6Ldkew0qAAAAANFhvgiOKViu_tduZTncnXJ8dRXi';

        // reCAPTCHA response verification
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secretAPIkey . '&response=' . $_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);

        if ($responseData->success) {
            // Check if the anti-spam field is filled
            if (!empty($_POST['human'])) {
                // If the anti-spam field is filled, consider it spam and don't send the email
                echo "<h2>Spam detected!</h2>";
                echo "<p>Your message has been flagged as spam and not sent.</p>";
            } else {
                // Send email
                $name = $_POST['name'];
                $email = $_POST['email'];
                $message = $_POST['message'];
                $to = '[email protected]';
                $subject = 'Message';

                $headers = "From: $emailrn";
                $headers .= "MIME-Version: 1.0rn";
                $headers .= "Content-type: text/html; charset=iso-8859-1rn";

                $body = "From: $namern";
                $body .= "E-Mail: $emailrn";
                $body .= "Message:rn $message";

                if (mail($to, $subject, $body, $headers)) {
                    echo '<p>Your message has been sent successfully!</p>';
                } else {
                    echo '<p>Something went wrong, go back and try again!</p>';
                }
            }
        } else {
            echo '<p>reCAPTCHA verification failed. Please try again.</p>';
        }
    } else {
        echo '<p>Please complete the reCAPTCHA.</p>';
    }
} else {
    echo '<p>Form not submitted properly.</p>';
}
?>

At firt the recaptcha check was in the wrong place and the form was sending without having to complete it, I changed it to check recapcha first before processing the rest of the form, now it takes me to action_page.php as though its sent but I am not recieiving any mail now, it was before.

PHP: Lazy-evaluated static variable

I have a function that is called many times that look like this:

function attachImagesToProduct(Product $csProduct) {
    $searchPath = realpath(__DIR__ . "/../images");
    $files = scandir($searchPath);
    $files = array_map(function ($file) use ($searchPath) {
        return $searchPath . "/" . $file;
    }, $files);
    
    // Does stuff
}

However, the biggest performance issue is on the scandir + array_map parts. I need to do these only one time. This is why I wanted to mark $files as static, but because they are not constant expressions I can’t. Is there any way to mark $files as “lazy-evaluated” static, then I can avoid to do this heavy stuff everytimes I call the function ?

array_filter() returning the entire array instead of just the key value

I am doing a work around with PHP array_filter() function. I am noticing a strange. Let me explain.

This is an array $languageDataArray:-

$languageDataArray = array(
    array(
        'id'  => 1,
        'language' => 'en',
        'name'  => 'little'
    ),
    array(
        'id'  => 2,
        'language' => 'fr',
        'name'  => 'petre'
    )
);

And this is my language iteration array $languageFolders:-

$languageFolders = array('en', 'fr');

Now I am running a loop through each language element of $languageFolders array, and when the value of the 'language' node/key of each element of $languageDataArray is not 'en', I am printing the value of 'name' node/key of each element of $languageDataArray

if(isset($languageFolders) && !empty($languageFolders)) {
  foreach($languageFolders as $keyLanguage => $rowLanguage) {
    if($rowLanguage !== 'en') {
      $translatedName = NULL;
      if(isset($languageDataArray) && !empty($languageDataArray)) {
        $translatedNameData = array_filter($languageDataArray, function($languageObject) use($rowLanguage) {
            if($languageObject['language'] === $rowLanguage) {
              echo $languageObject['name'] . "n";
              return $languageObject['name'];
            }
        });
        $translatedName  = array_shift($translatedNameData)['name'];
      }
      echo $translatedName;
    }
  }
}

In the code observe the two lines-

echo $languageObject['name'] . "n";
return $languageObject['name'];

Inside the array_filter() function, when I am doing echo $languageObject['name'];, only the name is displayed, but when I am trying to return $languageObject['name']; instead of just the name value, the entire array element is being returned;

if(isset($languageFolders) && !empty($languageFolders)) {
  foreach($languageFolders as $keyLanguage => $rowLanguage) {
    if($rowLanguage !== 'en') {
      $translatedName = NULL;
      if(isset($languageDataArray) && !empty($languageDataArray)) {
        $translatedNameData = array_filter($languageDataArray, function($languageObject) use($rowLanguage) {
            if($languageObject['language'] === $rowLanguage) {
              echo $languageObject['name'] . "n";
              return $languageObject['name'];
            }
        });
        $translatedName  = array_shift($translatedNameData)['name'];
      }
      echo $translatedNameData;
      echo $translatedName;
    }
  }
}

The loc echo $translatedNameData; throws error Warning: Array to string conversion in /tmp/t3ncOEgiEd.php on line 30

Even though I a trying to return only the value of name key, I am getting the entire array object. Why?

Codeigniter 3 won’t show in localhost

The output when I entered localhost/[folder_project_name]

For information, this folder I’ve got is the source code for my project. This source code given to me from the lead. I want to make similar laravel project from this old project that using old Codeigniter version 3.

And the previous database using mysql, now I want to take a peek by running this project through localhost for having full experience. And I’ve also set the config.php for connecting to the existing database I’ve imported to the localhost as well.

Cause I never held an Codeigniter projects before and only using Laravel as PHP Framework, I don’t know what to do. I beg your kindness to answer my simple question.

Why are the numeric data recorded in the MySQL database not displayed correctly on the site?

Hello dear developers.

I have a small problem with PHP and MySQL. So, the site is compiled with PHP, HTML and JS. I use MySQL as a database. The site is an exam site.

The problem is that the questions I write to the database through the admin panel are both written to the database and visible inside the site.

When the user looks at the tests, tests with answers given in letters work without problems. But tests whose answers are given in numbers either do not work or when you click on one answer, several answers are selected. I need the numerical answers to work normally on the site. I was using VARCHAR for answers in the database, then I changed it to TEXT. Again it doesn’t work. But let me note that the questions whose answers are written in letters work without problems. Also, I changed the answers I wrote in numbers, for example, “three” instead of 3, etc. there is no problem when writing. I only encounter such a situation when the answer is a number. I would like to note that there are questions whose numerical answers do not cause problems. So why do I have this problem in some questions and not in others?
The site is built with Bootstrap and PHP. Display of questions and selection of answers is done through JS. I also use 2 PHP files to download the questions from the database. I think there is something missing somewhere in one of them.

How to overcome this?
Please, those who know, answer.

Thanks in advance.

//action.php
<?php
require('../config.php');

if ($_GET['act'] == 'checkanswer') {
    $data = $_POST;
    $return_data = [];

    foreach ($data as $key => $val) {
        $parts = explode("_&&_", $val);

        $qid = $key;

        $val = $parts[0];
        $aorder = $parts[1];

        $sql = "SELECT correct_answer FROM mentiq WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $qid);
        $stmt->execute();
        $stmt->bind_result($correct_answer);
        $stmt->fetch();
        $stmt->close();

        $result = [];
        $result['true'] = ($correct_answer == $val ? 1 : 0);
        $result['choosed'] = $aorder;
        $result['correct'] = $correct_answer;
        $result['qid'] = $qid;

        $return_data[] = $result;
    }

    echo json_encode($return_data);
    exit;
}

?>
//load_questions.php
<?php
include('../config.php');

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$category_id_to_display = isset($_GET['category_id']) ? $_GET['category_id'] : 1;

$sql = "SELECT id, question, question_image, answer1, answer2, answer3, answer4, correct_answer FROM mentiq WHERE category_id = $category_id_to_display ORDER BY id";
$result = $conn->query($sql);

$questions = [];

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $questions[] = [
            'id' => $row["id"],
            'question' => $row["question"],
            'question_image' => $row["question_image"],
            'answer1' => $row["answer1"],
            'answer2' => $row["answer2"],
            'answer3' => $row["answer3"],
            'answer4' => $row["answer4"],
            'correct_answer' => $row["correct_answer"],
        ];
    }
}

echo json_encode($questions);

$conn->close();
?>
//section in website
<section class="courses-area pt-100 pb-70">
    <div class="container">
        <div class="row">
            <div id="questionsContainer" class="container"></div>
        </div>

        <script>
            var currentIndex = 0;
            var questions = [];
            var userAnswers = {};
            var answersSubmitted = false;

            $(document).ready(function () {
                function loadQuestions() {
                    $.ajax({
                        url: 'load_questions.php',
                        method: 'GET',
                        data: { category_id: 1 },
                        dataType: 'json',
                        success: function (data) {
                            questions = data;
                            showQuestion(currentIndex);
                        },
                        error: function (xhr, status, error) {
                            console.error('Error fetching questions.', status, error);
                        },
                    });
                }

               function showQuestion(index) {
    var question = questions[index];
    var answerLabels = ['A', 'B', 'C', 'D'];

    var questionHtml = '<h6 class="mb-3">';
    questionHtml += '<strong><label class="form-label mb-4">' + question.question + '</label></strong>';
    
    if (question.question_image) {
        questionHtml += '<br><img src="' + question.question_image + '" alt="Question Image" style="max-width:100%; height:auto;"><br>';
    }

    for (var i = 0; i < answerLabels.length; i++) {
        var answerKey = 'answer' + (i + 1);
        questionHtml += getAnswerOptionHtml(question, answerKey, answerLabels[i]);
    }

    questionHtml += '</div><hr class="my-4">';

    $('#questionsContainer').html(questionHtml);
    $('#nextBtn').prop('disabled', userAnswers[question.id] === undefined);
    if (answersSubmitted) {
        updateAnswerButtons();
    }
}

                function getAnswerOptionHtml(question, answerKey, answerLabel) {
    var answerHtml = '<br><button type="button" class="btn btn-light mb-3 answer-btn left-align-btn btn5" data-answer="' + question[answerKey] + '">' + answerLabel + ') ' + question[answerKey] + '</button>';
    return answerHtml;
}


                function updateAnswerButtons() {
                    questions.forEach(function (q) {
                        var userAnswer = userAnswers[q.id];
                        var selector = '.answer-btn[data-answer="' + userAnswer + '"]';

                        if (userAnswer === undefined) {
                            return;
                        }

                        if (userAnswer === q.correct_answer) {
                            $(selector).removeClass('btn-light').addClass('btn-success');
                        } else {
                            $(selector).removeClass('btn-light').addClass('btn-danger');
                            var correctAnswerSelector = '.answer-btn[data-answer="' + q.correct_answer + '"]';
                            $(correctAnswerSelector).removeClass('btn-light').addClass('btn-success');
                        }
                    });

                    if (Object.keys(userAnswers).length === questions.length) {
                        showScoreToast();
                    }
                }

                function showScoreToast() {
                    var trueAnswers = 0;

                    questions.forEach(function (q) {
                        var userAnswer = userAnswers[q.id];
                        if (userAnswer === q.correct_answer) {
                            trueAnswers++;
                        }
                    });

                    var totalPoints = trueAnswers;
                    var totalQuestions = questions.length;
                    var percentage = (totalPoints / totalQuestions) * 100;
                    var message;

                           if (percentage >= 80) {
                        message = 'Siz <strong>' + totalQuestions + '</strong> sualdan <strong>' + totalPoints + '</strong> bal topladınız. Bu əla nəticədir. Təbrik edirik!';
                    } else if (percentage >= 50) {
                        message = 'Siz <strong>' + totalQuestions + '</strong> sualdan <strong>' + totalPoints + '</strong> bal topladınız. Bu pis nəticə deyil. Təşəkkür edirik!';
                    } else {
                        message = 'Siz <strong>' + totalQuestions + '</strong> sualdan <strong>' + totalPoints + '</strong> bal topladınız. Bu çox pis nəticədir. Yenidən cəhd edin!';
                    }


                    $('#scoreMessage').html(message);
                    $('#scoreToast').toast('show');
                    
                    setTimeout(function () {
                        $('#scoreToast').toast('hide');
                    }, 60000);
                }

                $('body').on('click', '.answer-btn', function () {
                    var selectedAnswer = $(this).data('answer');
                    userAnswers[questions[currentIndex].id] = selectedAnswer;
                    updateAnswerButtons();
                    $('#nextBtn').prop('disabled', false);
                });

                $('#prevBtn').click(function () {
                    if (currentIndex > 0) {
                        currentIndex--;
                        showQuestion(currentIndex);
                    }
                });

                $('#nextBtn').click(function () {
                    if (currentIndex < questions.length - 1) {
                        currentIndex++;
                        showQuestion(currentIndex);
                    } else {
                        answersSubmitted = true;
                        updateAnswerButtons();
                    }
                });

                loadQuestions();
            });
        </script>
        
        <div id="scoreToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <strong class="me-auto"><i class="fa fa-calculator fa-2x" style="color:#A93226"></i> Sizin nəticəniz</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
                <div class="toast-body">
                    <strong>Əziz abunəçi!</strong>
                    <span id="scoreMessage"></span>
                </div>
        </div>
        <br>

        <div class="btn-group mb-10" role="group" aria-label="Navigation buttons">
            <button id="prevBtn" class="btn btn-warning" aria-disabled="true" style="margin-right: 10px; padding: 5px 10px;">Əvvəlki</button>
            <button id="nextBtn" class="btn btn-warning" disabled style="margin-right: 10px; padding: 5px 10px;">Sonrakı</button>
            <a href="../mst.php" class="btn btn-danger" style="margin-right: 10px; padding: 5px 10px;">Kateqoriyaya qayıt</a>
            <button class="btn btn-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample"><i class="fa fa-info"></i></button>
        </div>
       
            
            <div class="collapse mb-3" id="collapseExample">
                 <br>
              <div class="card card-body">
                <p><strong>Dəyərli abunəçi!</strong> <br>
                Qeyd etmək istəyirik ki, bir suala cavab vermədən növbəti suala keçmək mümkün deyil. 
                Əgər siz hansısa suala səhv cavab vermisinizsə onda bu cavab qırmızı rəng və düzgün cavab isə yaşıl rəng ilə göstəriləcək. 
                Bu kateqoriyada olan testlərin sonunda neçə bal topladığınızı görmüş olacaqsınız. Bildirmək istəyirik ki, balların qiymətləndirilməsi hər düzgün cavaba 1 bal verilməklə hesablanır və səhv cavabların sayı qeydə alınmır.<br>
            <strong>Uğurlar!</strong></p>
              </div>
            </div>
        
    </div>
</section>
//MySQL table
CREATE TABLE `mentiq` (
  `id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  `question` text NOT NULL,
  `answer1` varchar(500) NOT NULL,
  `answer2` varchar(500) NOT NULL,
  `answer3` varchar(500) NOT NULL,
  `answer4` varchar(500) NOT NULL,
  `correct_answer` varchar(500) NOT NULL,
  `question_image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;

Please, help me for editing files and solving this problem.

Sms Onay Servisi

Sms Onay

Bu sitemde arama menüsü çalışmıyor.

İstenilen servisin adını yazınca o servisle ilgili bilgi gelmesi gerekiyor. Bu konuda yardımcı olabilecek var mı ?

JavaScript ile düzenlenme yapılması gerekiyor.

PHP ile yazılmıştır.

Upwork API get a token

I have already received the authorization code. But the token cannot be obtained.

Documentation:
https://www.upwork.com/developer/documentation/graphql/api/docs/index.html#auth-authorizationCodeGrant

Endpoint

POST https://api.upwork.com/graphql/api/v3/oauth2/token‍

I do OAuth2 authorization using the league/oauth2-client library

My code:

include "lib/League/autoload.php";

use LeagueOAuth2ClientProviderGenericProvider;

// OAuth2
$provider = new GenericProvider([
    'clientId'                => '*****',
    'clientSecret'            => '*****',
    'redirectUri'             => '********',
    'urlAccessToken'          => 'https://api.upwork.com/graphql/api/v3/oauth2/token',
    'urlAuthorize'            => '', 
    'urlResourceOwnerDetails' => '',
]);


try {
    $accessToken = $provider->getAccessToken('authorization_code', [
        'code' => '*******' 
    ]);

    echo 'Access Token: ' . $accessToken->getToken() . "<br>";
    echo 'Expires: ' . $accessToken->getExpires() . "<br>";
} catch (LeagueOAuth2ClientProviderExceptionIdentityProviderException $e) {
    exit($e->getMessage());
}

After execution, I get an error:

Fatal error: Uncaught UnexpectedValueException: Invalid response received from Authorization Server. Expected JSON. in /lib/League/league/oauth2-client/src/Provider/AbstractProvider.php:637

If you do a normal POST CURL request, Upwork returns an HTML page with the title “Just moment…” and other content and nothing else happens..

Please tell me how to get this token.

WooCommerce Date of Birth Field on Checkout Page

Is anyone know how to add a mandatory “Date of Birth” field to WooCommerce Checkout Page?
The solution needs to be compatible with the WooCommerce “Blocks” type of Checkout Page template, not the shortcoded one.

I tried different snippets to make it work and also some plugin but all of them only works if I switch back to the old “shortcoded” WooCommerce Checkout template.
I need a solution whats compatible with the new “Blocks” tempalte. Is anyone know how should I achive this?

Pusher error 0A000438:SSL routines::tlsv1 alert internal error

I’m using Laravel Reverb on my live server. I’ve configured it to run with Nginx. However, I’m getting the following error whenever I try to broadcast an event using Reverb.

Pusher error: cURL error 35: OpenSSL/3.0.13: error:0A000438:SSL routines::tlsv1 alert internal error (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://ws.{domain_name}.app/apps/app_123/events?auth_key=key_123&auth_timestamp=1720515425&auth_version=1.0&body_md5=bea8622c84688147d1e7823170cee4fe&auth_signature=4f8b1ab60ac7f3e73a1746fc32ad4dedb2a50e9e625c84525d2d7f1c9099bc67.

This is the reverb stuff from my env:

 REVERB_APP_ID={app_id}
 REVERB_APP_KEY={app_key}
 REVERB_APP_SECRET={app_secret]
 REVERB_HOST="ws.{domain_name}.app"
 REVERB_SCHEME=https
 REVERB_SERVER_PORT=8080
 REVERB_PORT=443

This is my nginx configuration:

 # Define the server for {domain_name}.app and www.{domain_name}.app
 server {
     listen 80;
     server_name {domain_name}.app www.{domain_name}.app;
 
     # Define the root directory for the site
     root /home/digitalocean/{domain_name}.app/current/public;
 
     # Enable Gzip compression
     gzip on;
     gzip_types text/plain application/json text/css application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
 
     # Enable Zstd compression (requires Nginx to be compiled with Zstd support)
     # Uncomment the lines below if Zstd is supported
     # zstd on;
     # zstd_types text/plain application/json text/css application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
 
     location ~ ^/(app|apps)/ {
         proxy_http_version 1.1;
         proxy_set_header Host $http_host;
         proxy_set_header Scheme $scheme;
         proxy_set_header SERVER_PORT $server_port;
         proxy_set_header REMOTE_ADDR $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection "Upgrade";
 
         proxy_pass http://0.0.0.0:8080;
     }
 
     # PHP-FPM configuration
     location ~ .php$ {
         include fastcgi_params;
         fastcgi_pass unix:/run/php/php8.3-fpm.sock;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
         fastcgi_param SCRIPT_NAME $fastcgi_script_name;
     }
 }
 
 # Define the server for client.{domain_name}.app
 server {
     listen 80;
     server_name client.{domain_name}.app;
 
     # Enable Gzip compression
     gzip on;
     gzip_types text/plain application/json text/css application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
 
     # Reverse proxy to backend server
     location / {
         proxy_pass http://0.0.0.0:3000;
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header X-Forwarded-Proto $scheme;
     }
 }
 
 # Define the server for customer.{domain_name}.app
 server {
     listen 80;
     server_name customer.{domain_name}.app;
 
     # Enable Gzip compression
     gzip on;
     gzip_types text/plain application/json text/css application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
 
     # Reverse proxy to backend server
     location / {
         proxy_pass http://0.0.0.0:4000;
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header X-Forwarded-Proto $scheme;
     }
 }

Note: I’ve tried setting the REVERB_SCHEME as HTTP and the REVERB_PORT as 80; however, the error persists.