Create shortcode for each dimension property based on product ID in WooCommerce

Summarize:
Woocommerce product dimensions are length, width and height
Scope of this question is to create a shortcode for each product dimension property individually based on product ID.

Problem:
I found many sources and no one split the dimensions in three single shortcode attribute, like in Display WooCommerce Product Dimensions via a Shortcode answer thread.

This is an example on how Display WooCommerce Product Dimensions via a Shortcode.
I don’t know how to show attribute in near.

Description:
Add where needed a shortcode for Lenght
[user_meta id="35" key="lenght"]
Add where needed a shortcode for Width
[user_meta id="35" key="width"]
Add where needed a shortcode for Height
[user_meta id="35" key="height"]

Expections:
Something like this with a shortcode foreach dimensions

add_action( 'woocommerce_after_shop_loop_item', 'aman_show_product_dimensions', 20 );
  
function aman_show_product_dimensions() {
   global $product;
   $dimensions = $product->get_dimensions();
   if ( ! empty( $dimensions ) ) {
      echo '<div class="dimensions"><b>Height:</b> ' . $product->get_height() . get_option( 'woocommerce_dimension_unit' );
      echo '<br><b>Width:</b> ' . $product->get_width() . get_option( 'woocommerce_dimension_unit' );
      echo '<br><b>Length:</b> ' . $product->get_length() . get_option( 'woocommerce_dimension_unit' );
      echo '</div>';        
   }
}

PHP Leaf framework – db()->lastInsertId() returns “0”

I have issue with PHP Leaf framework database operation which returns “0” instead of last inserted record id.

My PHP version is 8.2.12.

There is a code.

app/routes/__app.php

app()->get('/apiv1/test', function () {
    $res = db()
    ->insert('item_schemas')
    ->params([
        'table_name' => 'hat',
        'created_at' => Carbon::now(),
        'updated_at' => null
    ])->execute();

    $itemSchemaId = db()->lastInsertID();

    response()->json([
        'itemSchemaId' => $itemSchemaId,
        'errors' => $res ? 'No errors' : db()->errors(),
        'res' => $res
    ]);
});

public/index.php

<?php

/*
|--------------------------------------------------------------------------
| Switch to root path
|--------------------------------------------------------------------------
|
| Point to the application root directory so leaf can accurately
| resolve app paths.
|
*/
chdir(dirname(__DIR__));

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require dirname(__DIR__) . '/vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Bring in (env)
|--------------------------------------------------------------------------
|
| Quickly use our environment variables
|
*/
try {
    DotenvDotenv::createUnsafeImmutable(dirname(__DIR__))->load();
} catch (Throwable $th) {
    trigger_error($th);
}

/*
|--------------------------------------------------------------------------
| Load application paths
|--------------------------------------------------------------------------
|
| Decline static file requests back to the PHP built-in webserver
|
*/
if (php_sapi_name() === 'cli-server') {
    $path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

    if (is_string($path) && __FILE__ !== $path && is_file($path)) {
        return false;
    }

    unset($path);
}

/*
|--------------------------------------------------------------------------
| Attach blade view
|--------------------------------------------------------------------------
|
| Templating has been disabled because you chose the MVC for APIs starter.
| If you want to use blade in your application,
| you can uncomment the line below.
|
*/
// LeafConfig::attachView(LeafBlade::class);

/*
|--------------------------------------------------------------------------
| Load Leaf configuration
|--------------------------------------------------------------------------
|
| Leaf MVC allows you to customize Leaf and it's modules using
| configuration files defined in the config folder. This line
| loads the configuration files and makes them available to
| your application.
|
*/
LeafCore::loadApplicationConfig();




/*
|--------------------------------------------------------------------------
| Sync Leaf Db with ORM and connect
|--------------------------------------------------------------------------
|
| Sync Leaf Db with ORM and connect to the database
| This allows you to use Leaf Db without having
| to initialize it in your controllers.
|
| If you want to use a different connection from those
| used in your models, you can remove the line below and
| add your own connection with:
| db()->connect(...)
|
| **Uncomment the line below to use Leaf Db**
| **You don't need this line to use Leaf Auth**
*/

db()->autoConnect();

/*
|--------------------------------------------------------------------------
| Load custom libraries
|--------------------------------------------------------------------------
|
| You can load your custom libraries here. If you have
| anything defined in your lib folder, you can load
| them here. Simply uncomment the line below.
|
*/
// LeafCore::loadLibs();

/*
|--------------------------------------------------------------------------
| Run your Leaf MVC application
|--------------------------------------------------------------------------
|
| This line brings in all your routes and starts your application
|
*/

LeafCore::runApplication();

composer.json

{
    "name": "leafs/mvc",
    "version": "3.9.1",
    "description": "A lightweight PHP MVC framework powered by Leaf",
    "type": "library",
    "keywords": [
        "framework",
        "leaf",
        "leafPHP",
        "mvc",
        "leaf mvc"
    ],
    "license": "MIT",
    "authors": [
        {
            "name": "Michael Darko",
            "email": "[email protected]",
            "homepage": "https://mychi.netlify.app",
            "role": "Maintainer"
        },
        {
            "name": "Abdulbasit Rubeya",
            "email": "[email protected]",
            "homepage": "https://github.com/ibnsultan",
            "role": "Maintainer"
        }
    ],
    "require": {
            "leafs/blade": "*",
            "leafs/mvc-core": "^1.11",
            "leafs/leaf": "^3.7",
            "leafs/csrf": "*",
            "leafs/logger": "v2.0",
            "leafs/cors": "*",
            "leafs/auth": "^3.0",
            "leafs/db": "*",
            "leafs/vite": "^0.3.0",
            "leafs/form": "^3.0",
            "leafs/http": "^3.0",
            "leafs/aloe": "^2.3",
            "leafs/fs": "v2.0"
    },
    "require-dev": {
        "fakerphp/faker": "^1.16",
        "leafs/alchemy": "^2.0"
    },
    "autoload": {
        "psr-4": {
            "App\": "app/",
            "Tests\": "tests/",
            "Config\": "config/",
            "App\Http\": "app/http/",
            "App\Jobs\": "app/jobs/",
            "App\Lang\": "app/lang/",
            "App\Mail\": "app/mail/",
            "App\Views\": "app/views/",
            "App\Utils\": "app/utils/",
            "App\Events\": "app/events/",
            "App\Models\": "app/models/",
            "App\Mailers\": "app/mailers/",
            "App\Workers\": "app/workers/",
            "App\Console\": "app/console/",
            "App\Scripts\": "app/scripts/",
            "App\Helpers\": "app/helpers/",
            "App\Channels\": "app/channels/",
            "App\Services\": "app/services/",
            "App\Middleware\": "app/middleware/",
            "App\Components\": "app/components/",
            "App\Controllers\": "app/controllers/",
            "App\Notifications\": "app/notifications/",
            "App\Database\Seeds\": "app/database/seeds/",
            "App\Database\Schema\": "app/database/schema/",
            "App\Database\Factories\": "app/database/factories/"
        },
        "exclude-from-classmap": [
            "app/database/migrations"
        ]
    },
    "config": {
        "optimize-autoloader": true,
        "sort-packages": false,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r "file_exists('.env') || copy('.env.example', '.env');"",
            "@php -r "if (file_exists('README2.MD')) {unlink('README.MD'); rename('README2.MD', 'README.MD');}""
        ],
        "post-create-project-cmd": [
            "@php leaf key:generate"
        ]
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

app/database/migrations/2025_03_18_075024_create_item_schema.php

<?php

use LeafDatabase;
use IlluminateDatabaseSchemaBlueprint;

class CreateItemSchema extends Database
{
    /**
     * Run the migrations.
     * @return void
     */
    public function up()
    {
        if (!static::$capsule::schema()->hasTable('item_schemas')) :
            static::$capsule::schema()->create('item_schemas', function (Blueprint $table) {
                $table->id();
                $table->string('table_name')->unique();
                $table->timestamp('created_at')->nullable();
                $table->timestamp('updated_at')->nullable();
            });
        endif;
    }

    /**
     * Reverse the migrations.
     * @return void
     */
    public function down()
    {
        static::$capsule::schema()->dropIfExists('item_schemas');
    }
}

all composer packages after command

composer show -i

carbonphp/carbon-doctrine-types  2.1.0    Types to use Carbon in Doctrine
doctrine/cache                   2.2.0    PHP Doctrine Cache library is a popular cache implementation that suppor...
doctrine/dbal                    3.9.4    Powerful PHP database abstraction layer (DBAL) with many features for da...
doctrine/deprecations            1.1.4    A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 loggin...
doctrine/event-manager           2.0.1    The Doctrine Event Manager is a simple PHP event system that was built t...
doctrine/inflector               2.0.10   PHP Doctrine Inflector is a small library that can perform string manipu...
fakerphp/faker                   v1.24.1  Faker is a PHP library that generates fake data for you.
firebase/php-jwt                 v6.11.0  A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Shou...
graham-campbell/result-type      v1.1.3   An Implementation Of The Result Type
illuminate/bus                   v8.83.27 The Illuminate Bus package.
illuminate/collections           v8.83.27 The Illuminate Collections package.
illuminate/container             v8.83.27 The Illuminate Container package.
illuminate/contracts             v8.83.27 The Illuminate Contracts package.
illuminate/database              v8.83.27 The Illuminate Database package.
illuminate/events                v8.83.27 The Illuminate Events package.
illuminate/filesystem            v8.83.27 The Illuminate Filesystem package.
illuminate/macroable             v8.83.27 The Illuminate Macroable package.
illuminate/pipeline              v8.83.27 The Illuminate Pipeline package.
illuminate/support               v8.83.27 The Illuminate Support package.
illuminate/view                  v8.83.27 The Illuminate View package.
jenssegers/blade                 v1.4.0   The standalone version of Laravel's Blade templating engine for use outs...
leafs/alchemy                    2.2      Integrated testing/style fixing tool for your PHP apps
leafs/aloe                       2.5.1    Overpowered command line tool for your leaf apps.
leafs/anchor                     v1.6.2   Leaf PHP util module
leafs/auth                       v3.4.1   Leaf PHP auth helper
leafs/blade                      v4.0     Leaf PHP Framework adaptation of jenssegers/blade package
leafs/cors                       v1.2     Leaf PHP cors config
leafs/csrf                       v0.5.4   Leaf CSRF security patch for leaf anchor
leafs/date                       v2.2     Leaf PHP date module
leafs/db                         v4.0.1   Leaf PHP db module.
leafs/exception                  v3.6.3   Error handler for leaf (fork of whoops)
leafs/form                       v3.2     Simple straightup data validation
leafs/fs                         v2.0     Leaf PHP session + flash modules
leafs/http                       v3.5     Http abstraction for Leaf PHP
leafs/leaf                       v3.12    Elegant PHP for modern developers
leafs/logger                     v2.0     Leaf PHP logger utility
leafs/mvc-core                   v1.11.1  Core files specific to MVC based leaf frameworks like Leaf MVC and Leaf ...
leafs/password                   v1.0     Leaf PHP password helper
leafs/session                    v4.0.1   Leaf PHP session + flash modules
leafs/vite                       v0.3.0   Server component for Vite
nesbot/carbon                    2.73.0   An API extension for DateTime that supports 281 different languages.
nikic/php-parser                 v4.19.4  A PHP parser written in PHP
phpoption/phpoption              1.9.3    Option Type for PHP
psr/cache                        3.0.0    Common interface for caching libraries
psr/clock                        1.0.0    Common interface for reading the clock.
psr/container                    1.1.2    Common Container Interface (PHP FIG PSR-11)
psr/log                          2.0.0    Common interface for logging libraries
psr/simple-cache                 1.0.1    Common interfaces for simple caching
psy/psysh                        v0.11.22 An interactive shell for modern PHP.
symfony/console                  v5.4.47  Eases the creation of beautiful and testable command line interfaces
symfony/deprecation-contracts    v3.5.1   A generic function and convention to trigger deprecation notices
symfony/finder                   v5.4.45  Finds files and directories via an intuitive fluent interface
symfony/polyfill-ctype           v1.31.0  Symfony polyfill for ctype functions
symfony/polyfill-intl-grapheme   v1.31.0  Symfony polyfill for intl's grapheme_* functions
symfony/polyfill-intl-normalizer v1.31.0  Symfony polyfill for intl's Normalizer class and related functions
symfony/polyfill-mbstring        v1.31.0  Symfony polyfill for the Mbstring extension
symfony/polyfill-php73           v1.31.0  Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions
symfony/polyfill-php80           v1.31.0  Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions
symfony/process                  v6.4.19  Executes commands in sub-processes
symfony/service-contracts        v3.5.1   Generic abstractions related to writing services
symfony/string                   v6.4.15  Provides an object-oriented API to strings and deals with bytes, UTF-8 c...
symfony/translation              v6.4.19  Provides tools to internationalize your application
symfony/translation-contracts    v3.5.1   Generic abstractions related to translation
symfony/var-dumper               v6.4.18  Provides mechanisms for walking through any arbitrary PHP variable
symfony/yaml                     v6.4.18  Loads and dumps YAML files
vlucas/phpdotenv                 v5.6.1   Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SE...
voku/portable-ascii              1.6.1    Portable ASCII library - performance optimized (ascii) string functions ...

And result is:

{
  "itemId": "0"
}

MySQL connection is established correct and record is inserted to the database, db()->lastInsertId() should returns valid record Id. Thanks very much for help.

EDIT:

Result after var_dump:

object(PDOStatement)#36 (1) {
  ["queryString"]=>
  string(78) "INSERT INTO item_schemas (table_name,created_at,updated_at) VALUES (?,?,?)"
}

API result:

{
"itemSchemaId": "0",
  "errors": "No errors",
  "res": {
    "queryString": "INSERT INTO item_schemas 
    (table_name,created_at,updated_at) VALUES (?,?,?)"
  }
}

After Explain query:

"query": [
{
  "id": 1,
  "select_type": "INSERT",
  "table": "item_schemas",
  "partitions": null,
  "type": "ALL",
  "possible_keys": null,
  "key": null,
  "key_len": null,
  "ref": null,
  "rows": null,
  "filtered": null,
  "Extra": null
}
],

Explain query:

$query = db()->query("EXPLAIN " . "INSERT INTO item_schemas (table_name,created_at,updated_at) VALUES ('glovesssssssssssssssdsssss','2025-03-23 10:29:29',NULL)")->all();

Table structure with EXPLAIN:

{
"query": [
{
"Field": "id",
"Type": "bigint(20) unsigned",
"Null": "NO",
"Key": "PRI",
"Default": null,
"Extra": "auto_increment"
},
{
"Field": "table_name",
"Type": "varchar(255)",
"Null": "NO",
"Key": "UNI",
"Default": null,
"Extra": ""
},
{
"Field": "created_at",
"Type": "timestamp",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
},
{
"Field": "updated_at",
"Type": "timestamp",
"Null": "YES",
"Key": "",
"Default": null,
"Extra": ""
}
}

Datatables Server Side Filtering Wrong When Have Space Character

Hello i create datatables serverside with PHP, but filtering result is wrong.
i want to show only 1 data, when i filter “epic 5” but the result show 5 data.
You can check my screenshot here : https://i.ibb.co.com/4RnRcwLg/Screenshot-1.png

When i debug SQL code show like this. Why datatables split my filtering?

SELECT
    `rank_star`.*,
    `rk`.`rank_name`,
    `usr`.`employee_username` 
FROM
    `rank_star`
    LEFT JOIN `rank` AS `rk` ON `rk`.`id_rank` = `rank_star`.`id_rank`
    LEFT JOIN `employee` AS `usr` ON `usr`.`employee_id` = `rank_star`.`created_by`
    LEFT JOIN `employee` AS `usr_up` ON `usr_up`.`employee_id` = `rank_star`.`updated_by` 
WHERE
    (
        LOWER( `rk`.`rank_name` ) LIKE % epic % 
        OR LOWER( `rank_star`.`rank_name_star` ) LIKE % epic % 
        OR LOWER( `rank_star`.`rank_star_order` ) LIKE % epic % 
        OR LOWER( `rank_star`.`created_at` ) LIKE % epic % 
        OR LOWER( `rank_star`.`updated_at` ) LIKE % epic % 
        OR LOWER( `usr`.`employee_username` ) LIKE % epic % 
    OR LOWER( `usr_up`.`employee_username` ) LIKE % epic %) 
    AND (
        LOWER( `rk`.`rank_name` ) LIKE % 5 % 
        OR LOWER( `rank_star`.`rank_name_star` ) LIKE % 5 % 
        OR LOWER( `rank_star`.`rank_star_order` ) LIKE % 5 % 
        OR LOWER( `rank_star`.`created_at` ) LIKE % 5 % 
        OR LOWER( `rank_star`.`updated_at` ) LIKE % 5 % 
        OR LOWER( `usr`.`employee_username` ) LIKE % 5 % 
    OR LOWER( `usr_up`.`employee_username` ) LIKE % 5 %) 
ORDER BY
    `rank_star`.`rank_star_order` ASC 
    LIMIT 100 OFFSET 0

This is my javasript code

$(document).ready(function(){
    $("#example").DataTable({
        search: { "bSmart": false, "bRegex": true },
        serverSide : true,
        processing : true,
        ajax : {
            url : "rank_star/res",
            type : 'POST',
            dataType : 'JSON',
            data : {_token : '{{csrf_token()}}'}
        },
        columns : [
            {data : 'act', name : 'act'},
            {data : 'rank_name', name : 'rk.rank_name'},
            {data : 'rank_name_star', name : 'rank_star.rank_name_star'},
            {data : 'rank_min_star', name : 'rank_min_star',className: "text-center"},
            {data : 'rank_max_star', name : 'rank_max_star',className: "text-center"},
            {data : 'rank_star_order', name : 'rank_star.rank_star_order',className: "text-center"},
            {data : 'created_date', name : 'created_at'},
            {data : 'updated_date', name : 'updated_at'},
            {data : 'employee_add', name : 'usr.employee_username'},
            {data : 'employee_update', name : 'usr_up.employee_username'},
        ],
        pageLength: 100,
        order: [[5, 'asc']],
    });
});

And this is my PHP Code

$data = RankStar::query()->select(
                                [
                                 'rank_star.*',
                                 'rk.rank_name',
                                 'usr.employee_username',
                                ]
                            )
                            ->leftJoin('rank as rk', 'rk.id_rank', '=', 'rank_star.id_rank')
                            ->leftJoin('employee as usr', 'usr.employee_id', '=', 'rank_star.created_by')
                            ->leftJoin('employee as usr_up', 'usr_up.employee_id', '=', 'rank_star.updated_by');
        return datatables()->eloquent($data)
        ->addColumn("act", function($row){

            $func_action ="";
            $btn_edit    = "<button type='button' title='Update' class='btn btn-primary btn-sm' onclick='do_edit("".$row->id_rank_star."")' data-toggle='modal' data-target='#update_modal'><i class='fa fa-pencil'></i></button>&nbsp;";
            $btn_delete  = "<button type='button' title='Delete' class='btn btn-danger btn-sm' onclick='do_delete("".$row->id_rank_star."")'><i class='fa fa-trash'></i></button>";
            
            if(acc_update(Session::get('ses_level'),$this->data['id_menu']) == '1'){
                     $func_action .= $btn_edit;
            }

            if(acc_delete(Session::get('ses_level'),$this->data['id_menu']) == '1'){
                    $func_action .= $btn_delete;
            }

            return "<center>".$func_action."</center>"; 
        })
        ->addColumn("rank_name", function($row){
            return @$row->rank_name;
        })
        ->addColumn("rank_name_star", function($row){
            return @$row->rank_name_star;
        })
        ->addColumn("rank_min_star", function($row){
            return @$row->rank_min_star;
        })
        ->addColumn("rank_max_star", function($row){
            return @$row->rank_max_star;
        })
        ->addColumn("rank_star_order", function($row){
            return @$row->rank_star_order;
        })
        ->addColumn("employee_add", function($row){
            return @$row->creator->employee_username;
        })
        ->addColumn("employee_update", function($row){
            return @$row->updater->employee_username;
        })
        ->addColumn("created_date", function($row){
            return get_date_indonesia($row->created_at)." ".substr($row->created_at, 10, 9);
        })
        ->addColumn("updated_date", function($row){
            return get_date_indonesia($row->updated_at)." ".substr($row->updated_at, 10, 9);
        })
        ->rawColumns(['act'])
        ->make(true);

Help me sir, thanks.

How to get isset() to execute MORE than once in PHP? [duplicate]

I’m trying to do something that should be simple. I want a button that every time it’s clicked to update an mysql row value to increment by 1. so click in ten times and the value is 10. I am trying to use isset() to do this, with just normal variables to test:

php:

   $amount = 0;

   if(isset($_POST['button1'])) {
   echo "button 1 clicked";
   $amount++;
   }

html:

<form method="post">
    <input class="button" type="submit" value="select" name="button1"></input>
</form>

<h1><?= $amount ?></h1>

this works, but only once. My thought was that since $_POST[‘button1’] is now set, it doesn’t execute again because it is only supposed to execute when the value is no longer null and that only happens once. so, I thought I’d try:

   unset($_POST[‘button1’]);

in the isset() block, or even:

   $_POST[‘button1’] = null;

so that the button click would hopefully redefine it, but no luck. what do I do? most questions want a button to click only once, but I want the opposite, for it to theoretically click forever. why can’t a button just call a function like in js? I know php probably isn’t the best choice for this kind of project, but is there a way?

FCM Auth2 subscribe to topic erro: Authentication using

I am trying to send a notification to a group of devices (topic) usin Auth2.
So first I tried to send a message to single device, and it worked OK.

Now I want to create the topic.
So I use this code that is attached at the bottom, but I get the result:

result= {“error”:”Authentication using server key is deprecated. Please use an OAuth2 token instead.”}

The access-token is the same as I use for sending one message.

The code:

$topic="{$card_id}_{$type}_{$locale}";
$url = "https://iid.googleapis.com/iid/v1:batchAdd";
$json=["to" => "/topics/{$topic}", "registration_tokens" => [$fcm_token]];
$result=send_2_FCM($json,$url);
function send_2_FCM($data,$url)
{
  require_once('firebase_access_token.php');
  $access_token=getAccessToken();

  $headers = array(
    "Authorization: Bearer $access_token",
    "Content-Type: application/json"
  );

  $ch = curl_init();
  curl_setopt( $ch,CURLOPT_URL,$url);
  curl_setopt( $ch,CURLOPT_POST,true);
  curl_setopt( $ch,CURLOPT_HTTPHEADER,$headers);
  curl_setopt( $ch,CURLOPT_RETURNTRANSFER,true);
  curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER,false);
  curl_setopt( $ch,CURLOPT_CAINFO, "cacert.pem");
  if ($data)
  {
    curl_setopt( $ch,CURLOPT_POSTFIELDS,json_encode($data));
  }
  $result = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  debug_log("send_2_FCM: result= $result");
  if ($result && strpos($result,'"error"')) return 0;
  return 1;
}

Failed to Generate UUID for ETX Receipt php

Issue: Error Creating UUID for ETX Receipt

Problem Statement:Despite following all the instructions provided by the source for generating a UUID for an ETX receipt, errors persist during the process.

Source Instructions Followed:The UUID generation steps were taken from the official guidelines available at:ETA Receipt Issuance FAQ – UUID Generation

Steps Taken:

Implemented the UUID generation logic as per the provided documentation.

Ensured all required parameters were correctly formatted and included.

Verified system date, time, and unique transaction identifiers.

Checked for any potential conflicts or duplicate values.

Attempted multiple runs with different test cases.

Encountered Errors:

Error messages related to UUID creation.

Request for Assistance:Seeking guidance on:

Debugging methods for UUID generation errors.

Confirming the correct implementation of the required format.

Understanding any additional requirements not explicitly mentioned in the documentation.

Any insights or solutions from those who have successfully generated UUIDs for ETX receipts would be greatly appreciated.

    /////// receiptData
    
    
    $date_now = gmdate("Y-m-dTH:i:sZ");
    
    
    $receiptData = [
       "header" => [
                    "dateTimeIssued" => $date_now,
                    "receiptNumber" => "11111",
                    "uuid" => "",
                    "previousUUID" => "",
                    "referenceOldUUID" => "",
                    "currency" => "EGP",
                    "exchangeRate" => 0,
                    "sOrderNameCode" => "sOrderNameCode",
                    "orderdeliveryMode" => "",
                    "grossWeight" => 6.58,
                    "netWeight" => 6.89
                ],
                "documentType" => [
                    "receiptType" => "S",
                    "typeVersion" => "1.2"
                ],
                "seller" => [
                    "rin" => "249628635",
                    "companyTradeName" => "Mahmoud Mahros",
                    "branchCode" => "0",
                    "branchAddress" => [
                        "country" => "EG",
                        "governate" => "cairo",
                        "regionCity" => "city center",
                        "street" => "16 street",
                        "buildingNumber" => "14BN",
                        "postalCode" => "74235",
                        "floor" => "1F",
                        "room" => "3R",
                        "landmark" => "tahrir square",
                        "additionalInformation" => "talaat harb street"
                    ],
                    "deviceSerialNumber" => "100010001010",
                    "syndicateLicenseNumber" => "100010001010",
                    "activityCode" => "4922"
                ],
                "buyer" => [
                    "type" => "P",
                    "id" => "29308263200032",
                    "name" => "mahmoud mahros",
                    "mobileNumber" => "+201020567462",
                    "paymentNumber" => "987654"
                ],
                "itemData" => [
                    [
                        "internalCode" => "880609",
                        "description" => "Samsung A02 32GB_LTE_BLACK_DS_SM-A022FZKDMEB_A022 _ A022_SM-A022FZKDMEB",
                        "itemType" => "EGS",
                        "itemCode" => "EG-249628635-1",
                        "unitType" => "EA",
                        "quantity" => 35,
                        "unitPrice" => 247.96000,
                        "netSale" => 7810.74000,
                        "totalSale" => 8678.60000,
                        "total" => 8887.04360,
                        "commercialDiscountData" => [
                            [
                                "amount" => 867.86000,
                                "description" => "XYZ",
                                "rate" => 2.3
                            ]
                        ],
                        "itemDiscountData" => [
                            [
                                "amount" => 10,
                                "description" => "ABC",
                                "rate" => 2.3
                            ],
                            [
                                "amount" => 10,
                                "description" => "XYZ",
                                "rate" => 4.0
                            ],
                            [
                                "amount" => 11,
                                "description" => "SSS",
                                "rate" => 4.0
                            ]
                        ],
                        "valueDifference" => 20,
                        "taxableItems" => [
                            [
                                "taxType" => "T1",
                                "amount" => 1096.30360,
                                "subType" => "V009",
                                "rate" => 14
                            ]
                        ]
                    ]
                ],
                "totalSales" => 8678.60000,
                "totalCommercialDiscount" => 867.86000,
                "totalItemsDiscount" => 20,
                "extraReceiptDiscountData" => [
                    [
                        "amount" => 0,
                        "description" => "ABC",
                        "rate" => 10
                    ]
                ],
                "netAmount" => 7810.74000,
                "feesAmount" => 0,
                "totalAmount" => 8887.04360,
                "taxTotals" => [
                    [
                        "taxType" => "T1",
                        "amount" => 1096.30360
                    ]
                ],
                "paymentMethod" => "C",
                "adjustment" => 0,
                "contractor" => [
                    "name" => "contractor1",
                    "amount" => 2.563,
                    "rate" => 2.3
                ],
                "beneficiary" => [
                    "amount" => 20.569,
                    "rate" => 2.147
                ]
            ];
    
    
     function generateReceiptUUID(array $receipt): string {
        // Ensure UUID is empty before generation
        $receipt['header']['uuid'] = "";
    
        // Normalize the receipt object by serializing and flattening
        $normalizedString = normalizeReceipt($receipt);
    
        // Create SHA-256 hash
        $hash = hash('sha256', $normalizedString);
    
        return strtoupper($hash); // Convert to uppercase (if required)
    }
    
    function normalizeReceipt(array $receipt): string {
        // Sort keys to maintain consistency
        ksort($receipt);
    
        $normalizedString = "";
        foreach ($receipt as $key => $value) {
            if (is_array($value)) {
                // Recursive call for nested arrays
                $normalizedString .= strtoupper($key) . normalizeReceipt($value);
            } else {
                // Append key and value in normalized format
                $normalizedString .= strtoupper($key) . '"' . $value . '"';
            }
        }
    
        return $normalizedString;
    }
    
    $uuid = generateReceiptUUID($receiptData);
    
    $receiptData["header"]["uuid"] = $uuid;
    
    $formattedData = [
        "receipts" => [$receiptData] // تغليف البيانات داخل مصفوفة
    ];
    
    echo  $formattedData;
  

How to call vertex ai script from php from a browser url on a linux or Mac server?

I am trying to call a vertex ai generated python script to generate text from a php page and invoke it from a browser url.

The python script does not work on a linux or Mac server(but works on windows) when invoked from php through the browser url.

Interestingly the script works in terminal.

I am calling the vertex ai python script from php like this:

$Output = shell_exec(“python3 vertex.py”);

print($Output);

I am looking for a way to run the python script from the browser when called or invoked from the php script on a linux or macOS Server.

I am thinking that the issue could be due to/linked to handling virtual environment using php when the python script is invoked from the browser using php.

Bottom line it could be linked to the following underlying issues:

  1. How to handle google login/authentication for vertex scripts when called from the browser?

  2. It could also be linked to the handling of the virtual environment using php or python.

CPanel and WordPress Not Working – API 500 Error & No Website Access

CPanel and WordPress Not Working – API 500 Error & No Website Access

I am experiencing an issue with my cPanel. It was working fine, but sometimes it stopped due to an IP block. However, this time, the issue is different.

None of my websites are loading.

When I try to access WordPress via cPanel, it does not respond.

I am getting an API 500 error.

I cannot create new subdomains.

I have 15 websites on the same hosting, and all of them are down.

Additional Details:

Hosting plan: Premium

Storage: Sufficient available

What could be the possible reason for this issue, and how can I resolve it? Any guidance would be appreciated

Getting error “Cannot redeclare class __TwigTemplate”

Im trying to write twig loader that would load templates depending on the city and the partner who announced me in the app. And im getting error when i run my php app. Сlass is loaded correctly into the cache the first time, but then for some reason I try to create another class

Compile Error: Cannot redeclare class __TwigTemplate_91fb729aa360daba88c8f80ea708ed40 (previously declared in /var/www/var/cache/dev/twig/f1/f1f0c5a29775ffb735cb305c2a82df1f.php:16)

Here is my code:


readonly class PartnerTemplateLoader implements LoaderInterface
{
    const string DEFAULT_TEMPLATES_PATH = "Default";

    const string VIEWS_DIR = 'Resources/views';

    public function __construct(
        private KernelInterface $kernel,
        private Partner $partner,
        private City $city,
        private string $defaultTemplatesPath = self::DEFAULT_TEMPLATES_PATH
    ) {}

    public function getSourceContext($name): Source
    {
        $template = $this->loadTemplate($name);
        return new Source(
            file_get_contents(
                $this->kernel->locateResource($template->absoluteName)
            ),
            $template->name,
            $template->absoluteName
        );
    }

    public function getCacheKey($name): string
    {
        $template = $this->loadTemplate($name);
        return $template->name;
    }

    public function isFresh($name, $time): bool
    {
        $template = $this->loadTemplate($name);

        return filemtime($this->kernel->locateResource($template->absoluteName)) <= $time;
    }

    public function exists($name): bool
    {
       return $this->findTemplate($name);
    }

    private function loadTemplate(string $name): Template
    {
        $name = str_replace(
            ":/",
            ":",
            preg_replace("#/{2,}#", "/", strtr($name, "\", "/"))
        );

        if (str_contains($name, "..")) {
            throw new RuntimeException(
                sprintf('Template name "%s" contains invalid characters.', $name)
            );
        }

        preg_match('/^([^:]*)/([^:]*)/(.+).([^.]+).([^.]+)$/', $name, $matches);

        try {
            if (count($matches) === 0) {
                return new Template($name);
            }
        } catch (Throwable $e) {}

        try {
            $absoluteName = $this->prepareAbsolutePartnerName($matches, $this->city->getSlug());
            $name = $this->preparePartnerName($matches, $this->city->getSlug());
            if ($this->kernel->locateResource($absoluteName)) {
                return new Template($name, $absoluteName);
            }
        } catch (Throwable $e) {}

        try {
            $absoluteName = $this->prepareAbsolutePartnerName($matches, $this->defaultTemplatesPath);
            $name = $this->preparePartnerName($matches, $this->defaultTemplatesPath);
            if ($this->kernel->locateResource($absoluteName)) {
                return new Template($name, $absoluteName);
            }
        } catch (Throwable $exception) {}

        $absoluteName = $this->prepareAbsoluteDefaultName($matches);
        $name = $this->prepareDefaultName($matches);
        if ($this->kernel->locateResource($this->prepareAbsoluteDefaultName($matches))) {
            return new Template($name, $absoluteName);
        }

        throw new RuntimeException('Cannot load template!');
    }

    private function findTemplate(string $name): bool
    {
        $found = false;
        $name = str_replace(
            ":/",
            ":",
            preg_replace("#/{2,}#", "/", strtr($name, "\", "/"))
        );

        if (str_contains($name, "..")) {
            throw new RuntimeException(
                sprintf('Template name "%s" contains invalid characters.', $name)
            );
        }

        preg_match('/^([^:]*)/([^:]*)/(.+).([^.]+).([^.]+)$/', $name, $matches);

        try {
            if (count($matches) === 0 && $this->kernel->locateResource($name)) {
                $found = true;
            }
        } catch (Throwable $e) {}

        try {
            if ($this->kernel->locateResource($this->prepareAbsolutePartnerName($matches, $this->city->getSlug()))) {
                $found = true;
            }
        } catch (Throwable $e) {}

        try {
            if ($this->kernel->locateResource($this->prepareAbsolutePartnerName($matches, $this->defaultTemplatesPath))) {
                $found = true;
            }
        } catch (Throwable $e) {}

        try {
            if ($this->kernel->locateResource($this->prepareAbsoluteDefaultName($matches))) {
                $found = true;
            }
        } catch (Throwable $e) {}

        return $found;
    }

    private function prepareDefaultName(array $matches): string
    {
        return "{$matches[1]}/{$this->defaultTemplatesPath}/{$matches[2]}/{$matches[3]}.{$matches[4]}.{$matches[5]}";
    }

    private function preparePartnerName(array $matches, string $city): string
    {
        return "{$matches[1]}/{$this->partner->getTemplatesPath()}/{$city}/{$matches[2]}/{$matches[3]}.{$matches[4]}.{$matches[5]}";
    }

    private function prepareAbsoluteDefaultName(array $matches): string
    {
        $absoluteBundlePath =  $matches[1] . "/" . self::VIEWS_DIR;
        return "{$absoluteBundlePath}/{$this->defaultTemplatesPath}/{$matches[2]}/{$matches[3]}.{$matches[4]}.{$matches[5]}";
    }

    private function prepareAbsolutePartnerName(array $matches, string $city): string
    {
        $absoluteBundlePath =  $matches[1] . "/" . self::VIEWS_DIR;
        return "{$absoluteBundlePath}/{$this->partner->getTemplatesPath()}/{$city}/{$matches[2]}/{$matches[3]}.{$matches[4]}.{$matches[5]}";
    }
}

I tried to clear and warmup my cache and change template names

mysql gow can limk with my login to conect w external web [duplicate]

how can configur my login to mysql

Fatal error: Uncaught mysqli_sql_exception: Unknown database ‘login-php’ in C:xampphtdocsautenticacion.php:14 Stack trace: #0 C:xampphtdocsautenticacion.php(14): mysqli_connect(‘localhost’, ‘root’, Object(SensitiveParameterValue), ‘login-php’) #1 {main} thrown in C:xampphtdocsautenticacion.php on line 14

Ghostscript “gs” breaks imagick readImage for PDF

When everything is installed and setup regarding magick and if the Environment Variables path is also set, you should look at the installation folder which is usually located in C:Program Filesgsgs10.x .0bin. If there is no gs.exe and only gswin64.c.exe, copy that executable and change its name to gs.exe and readImage() will run the script.

With Laravel and php i have tried to convert pdf to png so i could use it for converting png image to zpl extension. Installing ghostscript for windows system didn’t help because file that are installed do not have proper name that class Imagick call and that name of executabel is “gs” and not “gswin64c”. Changing name help to solve problem and run ghostscript.

How to get custom variable price if bought in bulk (2x, 3x)

I want to have option to buy 2x or 3x product with discount (custom) price.
If chosen 2x or 3x all the attributes have same price.

The issue is that the custom price (e.g., 19.9) is not being applied to the cart item, and the base prices (price: “22.90”, regular_price: “34.90”) are still being used. This indicates that the custom price is not being properly passed to the server or applied to the cart item.

  1. Custom Price Not Applied:
    The custom price is sent to the server, but it is not being applied to the cart item.
    The base prices (price, regular_price, sale_price) are still being used.

  2. WooCommerce REST API Not Handling Custom Price:
    The WooCommerce REST API (/wp-json/wc/store/v1/batch) does not natively support custom prices. You need to handle this on the server side.

  3. JavaScript and PHP Integration:
    The JavaScript code sends the custom price to the server, but the PHP code is not properly applying it to the cart item.

To solve this problem, i need to:

  1. Ensure the Custom Price is Passed to the Server:
    The JavaScript code must send the custom price to the server when adding items to the cart.

  2. Apply the Custom Price to the Cart Item:
    Use WooCommerce hooks to override the product price when it is added to the cart.

  3. Retain the Custom Price in the Cart Session:
    Ensure the custom price is retained in the cart session after page refresh.

  4. Display the Custom Price in the Mini-Cart and Cart Page:
    Ensure the custom price is displayed correctly in the mini-cart and cart page.

My functions code:

function custom_pricing_options_html() {
    if (!is_product()) return;

    global $product;

    // Check if the product is simple or variable
    if (!$product->is_type('simple') && !$product->is_type('variable')) return;

    $product_id = $product->get_id();
    $currency = get_woocommerce_currency_symbol();

    // Get base prices
    $regular_price = $product->is_type('variable') 
        ? floatval($product->get_variation_regular_price('min')) 
        : floatval($product->get_regular_price());
    $sale_price = $product->is_type('variable') 
        ? floatval($product->get_variation_sale_price('min')) 
        : floatval($product->get_sale_price());

    // Get custom pricing options from ACF fields
    $price_option_2 = floatval(get_field('pricing_option_2', $product_id)) ?: 0;
    $price_option_3 = floatval(get_field('pricing_option_3', $product_id)) ?: 0;

    // Pricing options for 1x, 2x, and 3x
    $pricing_options = [
        1 => ['price' => $sale_price],
        2 => ['price' => $price_option_2],
        3 => ['price' => $price_option_3],
    ];

    ob_start();
    ?>

    <div class="pricing-container">
        <?php foreach ($pricing_options as $qty => $option) :
            if ($option['price'] <= 0) continue; // Skip empty values
        ?>
        <div class="pricing-option <?php echo $qty === 1 ? 'selected' : ''; ?>" 
            data-qty="<?php echo esc_attr($qty); ?>" 
            data-price="<?php echo esc_attr($option['price']); ?>" 
            data-currency-symbol="<?php echo esc_attr($currency); ?>">
    
            <div class="qty-discount-qty"><?php echo esc_html($qty); ?>x</div>
            <span class="qty-discount-price">
                <strong><?php echo esc_html($option['price'] . ' ' . $currency); ?></strong>
            </span>
            <div class="qty-discount-kos">per pair</div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Hidden field to store the selected price -->
    <input type="hidden" id="custom_selected_price" name="custom_selected_price" value="<?php echo esc_attr($sale_price); ?>">
    
   
    <?php
    echo ob_get_clean();
}
add_action('woocommerce_before_add_to_cart_form', 'custom_pricing_options_html');

// Save the selected price in cart item data
add_filter('woocommerce_add_cart_item_data', 'update_sale_price_in_cart', 10, 2);
function update_sale_price_in_cart($cart_item_data, $product_id) {
    if (isset($_POST['custom_selected_price'])) {
        $selected_price = floatval($_POST['custom_selected_price']);
        error_log('Selected Price in Cart: ' . $selected_price); // Debug
        $cart_item_data['custom_price'] = $selected_price;
    }
    return $cart_item_data;
}

// Apply the custom price to the cart item
add_action('woocommerce_before_calculate_totals', 'apply_custom_price_to_cart', 20);
function apply_custom_price_to_cart($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;

    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if (isset($cart_item['custom_price'])) {
            $custom_price = floatval($cart_item['custom_price']);
            $cart_item['data']->set_price($custom_price); // Override base price
        }
    }
}

// Retain the custom price in the cart after page refresh
add_filter('woocommerce_get_cart_item_from_session', 'retain_custom_price_in_cart', 10, 2);
function retain_custom_price_in_cart($cart_item, $values) {
    if (isset($values['custom_price'])) {
        error_log('Retaining Custom Price: ' . $values['custom_price']); // Debug
        $cart_item['custom_price'] = $values['custom_price'];
    }
    return $cart_item;
}

// Display custom price in mini-cart and cart page
function display_custom_price_in_cart($price, $cart_item, $cart_item_key) {
    if (isset($cart_item['custom_price'])) {
        $price = wc_price($cart_item['custom_price']);
    }
    return $price;
}
add_filter('woocommerce_cart_item_price', 'display_custom_price_in_cart', 10, 3);
add_filter('woocommerce_cart_item_subtotal', 'display_custom_price_in_cart', 10, 3);

// AJAX Handler for Adding to Cart with Custom Price
add_action('wp_ajax_add_to_cart_with_custom_price', 'add_to_cart_with_custom_price');
add_action('wp_ajax_nopriv_add_to_cart_with_custom_price', 'add_to_cart_with_custom_price');
function add_to_cart_with_custom_price() {
    if (!isset($_POST['product_id']) || !isset($_POST['custom_price'])) {
        wp_send_json_error('Invalid request.');
    }

    $product_id = intval($_POST['product_id']);
    $quantity = intval($_POST['quantity']);
    $custom_price = floatval($_POST['custom_price']);

    // Add product to cart
    $cart_item_key = WC()->cart->add_to_cart($product_id, $quantity);

    if ($cart_item_key) {
        // Set custom price in cart item data
        WC()->cart->cart_contents[$cart_item_key]['custom_price'] = $custom_price;
        WC()->cart->set_session();

        // Recalculate totals to apply the custom price
        WC()->cart->calculate_totals();

        wp_send_json_success('Product added to cart.');
    } else {
        wp_send_json_error('Failed to add product to cart.');
    }
}

My javascript:


jQuery(document).ready(function ($) {
    const $body = $('body');
    const $pricingOptions = $('.pricing-option');
    const $customSelectedPrice = $('#custom_selected_price');
    const $addToCartButton = $('.single_add_to_cart_button');

    // Event delegation for pricing options
    $body
        .on('click', '.pricing-option', function () {
            $pricingOptions.removeClass('selected');
            $(this).addClass('selected');

            const qty = $(this).data('qty');
            const price = $(this).data('price');

            // Debug: Log the selected price
            console.log('Selected Price:', price);

            // Update the hidden input field
            $customSelectedPrice.val(price);

            duplicateVariationSelection(qty);
            updatePriceTotal();
            updateSimpleQuantity(qty);
            maybeDisableVariableAddToCartButton();
        })
        .on('click', '.qty-appended .filter-item-list li', function () {
            $(this).parents('.qty-appended').find('.filter-item-list li').removeClass('active');
            $(this).addClass('active');
            maybeDisableVariableAddToCartButton();
        })
        .on('click', '.product-type-variable .single_add_to_cart_button', function (e) {
            e.preventDefault();

            const selectedPrice = $customSelectedPrice.val();
            console.log('Price sent to server:', selectedPrice);

            if ($(this).hasClass('wc-variation-selection-needed') && $('.qty-appended').length > 0) {
                alert('Please select all variations before adding to cart.');
                return;
            }

            addAppendedItemsToCart(selectedPrice);
        });

    // Duplicate variations based on selected quantity
    function duplicateVariationSelection(qty) {
        if ($('.product-type-variable').length <= 0) return;

        const label = $('.variations .label label').first().text();
        const list = $('.variations .value ul.filter-item-list').clone().html().replace(/active/g, '');

        $('.qty-appended').remove(); // Remove previous appended rows

        for (let i = 2; i <= qty; i++) {
            $('.variations tbody').append(`
                <tr class="qty-appended qty-${i}">
                    <th class="label"><label>${label} ${i}</label></th>
                    <td><ul class="filter-item-list">${list}</ul></td>
                </tr>`);
        }

        maybeDisableVariableAddToCartButton();
    }

    // Enable/disable the "Add to Cart" button based on selected variations
    function maybeDisableVariableAddToCartButton() {
        const totalAppended = $('.qty-appended').length;
        const totalSelected = $('.filter-item-list li.active').length;

        $addToCartButton.prop('disabled', totalAppended + 1 !== totalSelected);
    }

    // Add items to the cart
    function addAppendedItemsToCart() {
        const attributeName = $('[data-attribute_name]').data('attribute_name');
        const variationData = $('[data-product_variations]').data('product_variations');
        const totalAppended = $('.qty-appended').length;
        const selectedPrice = $('.pricing-option.selected').data('price'); // Get selected price
        let cartData = [];
    
        let itemAttributeOriginal = $('table.variations tr:not(.qty-appended) li.active a').data('value');
    
        // Original selected variation.
        $.each(variationData, function (key, value) {
            if (value['attributes'][attributeName] === itemAttributeOriginal) {
                cartData.push({
                    path: '/wc/store/v1/cart/add-item',
                    method: 'POST',
                    headers: {
                        'Nonce': product_js_vars.woononce
                    },
                    body: {
                        id: value.variation_id,
                        quantity: 1,
                        custom_price: selectedPrice // Include custom price
                    }
                });
            }
        });
    
        // If multiple appended
        if ($('.qty-appended').length > 0) {
            for (let i = 1; i < totalAppended + 1; i++) {
                let counter = i + 1;
                const itemAttribute = $(`.qty-${counter} .filter-item-list li.active a`).data('value');
    
                $.each(variationData, function (key, value) {
                    if (value['attributes'][attributeName] === itemAttribute) {
                        cartData.push({
                            path: '/wc/store/v1/cart/add-item',
                            method: 'POST',
                            headers: {
                                'Nonce': product_js_vars.woononce
                            },
                            body: {
                                id: value.variation_id,
                                quantity: 1,
                                custom_price: selectedPrice // Include custom price
                            }
                        });
                    }
                });
            }
        }
    
        $.ajax({
            url: '/wp-json/wc/store/v1/batch',
            method: 'POST',
            dataType: 'json',
            headers: {
                'Nonce': product_js_vars.woononce
            },
            data: {
                requests: cartData
            },
            success: function (response) {
                console.log("Items added to cart:", response);
            },
            error: function (xhr) {
                console.error('Error adding item to cart:', xhr.responseJSON);
            }
        });
    }

    // Update the displayed price
    function updatePriceTotal() {
        const selectedOption = $('.pricing-option.selected');
        const price = selectedOption.data('price');
        const qty = selectedOption.data('qty');
        const percent = selectedOption.data('percent');
        const regular = selectedOption.data('regular');
        const currency = selectedOption.data('currency-symbol');

        const totalRegular = (regular * qty).toFixed(2);
        const totalPrice = (price * qty).toFixed(2);

        $('.price-placeholder').html(`
            <div class="variable-price-box">
                <div class="left-price-wrapper">
                    <div class="limited-offer-label">Quantity: ${qty}</div>
                    <div class="discount-badge-price">-${percent}% discount</div>
                </div>
                <div>
                    <del>${totalRegular} ${currency}</del>
                    <ins>${totalPrice} ${currency}</ins>
                </div>
            </div>`);
    }

    // Update quantity for simple products
    function updateSimpleQuantity(qty) {
        if ($('.product-type-variable').length > 0) return;
        $('form.cart .quantity input.qty').val(qty).trigger('change');
    }
});

How to test and share PHP and MySQL code together [closed]

I’m looking for an open-source online development environment or fiddle, similar to JSFiddle, that allows me to create and share small PHP and MySQL code snippets. My goal is to build proof-of-concept examples that I can share in Stack Overflow answers, where viewers can test the code live without needing to set up their own server environments.

Ideally, the tool should support both PHP scripts and MySQL queries, providing a quick and easy way to demonstrate server-side code and database interactions directly in the browser.

Does anyone know of a platform or tool that fits this use case, where I can generate and share these kinds of live demos without any server configuration?

Query with nulls and apostrophes returning syntax error using PDO bindParam (PHP) [duplicate]

I’ve been trying for hours to figure out what I’m doing wrong. The $trackName variable may include apostrophes. Also, some of the $subgenre and $mood variables may be NULL. This is my PHP code:

$sg2 = is_null($subgenre_2) ? NULL : $subgenre_2;
$sg3 = is_null($subgenre_3) ? NULL : $subgenre_3;
$sg4 = is_null($subgenre_4) ? NULL : $subgenre_4;
$sg5 = is_null($subgenre_5) ? NULL : $subgenre_5;

$md2 = is_null($mood_2) ? NULL : $mood_2;
$md3 = is_null($mood_3) ? NULL : $mood_3;

$query = "INSERT INTO `songs` (song_id, username, subgenre_1, subgenre_2, subgenre_3, subgenre_4, ";
$query .= "subgenre_5, mood_1, mood_2, mood_3, name, artist_name, active) ";
$query .= "VALUES ('" . $_SESSION['new_TK_data']['song-id'] . "', '" . $_SESSION['username'] ."', '";
$query .= $subgenre_1 . "', " . $sg2 . ", " . $sg3 . ", " . $sg4 . ", " . $sg5 . ", '";
$query .= $mood_1 . "', " . $md2 . ", " . $md3 . ", :name, '";
$query .= $_SESSION['new_TK_data']['artist_name'] . "', 1)";

$trackName = $_SESSION['new_TK_data']['name'];

$stmt = $pdo->prepare($query);
$stmt->bindParam(':name', $trackName, PDO::PARAM_STR);
$stmt->execute();    

This is what $query shows before binding:

INSERT INTO `songs` (song_id, username, subgenre_1, subgenre_2, subgenre_3, subgenre_4, subgenre_5, mood_1, mood_2, mood_3, name, artist_name, active) 
VALUES ('1peKZ91pGaS7QXzDBrICRy', 'romotony11', 'CONPNO', NEOCLA, SOLOPN, , , '6565', 4090, 1565, :name, 'Antonio Romo', 1)

This is the error I get:

Query failed: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘ , ‘6565’, 4090, 1565, ‘Twilight Mood’, ‘Antonio Romo’, 1)’ at line 1

I’m not sure if the error comes from the null values, or from the single quotes missing in some values than come from variables, or from something else. I’ve tried many different things without success. Any help will be appreciated!