Could not convert PHP value of type DateTimeImmutable to type DoctrineDBALTypesDateTimeType

I have a Symfony Command that reads rows from a spreadsheet and inserts them into a MySQL table. The command was working fine in Symfony 4.4. I started getting this error after I upgraded my version of Symfony and PHP.

DoctrineDBALTypesExceptionInvalidType: Could not convert PHP value of type DateTimeImmutable to type DoctrineDBALTypesDateTimeType. Expected one of the following types: null, DateTime.

This is the code that seems to be throwing the error

$accountstatement->setAccountStatementCreatedOn(new DateTimeImmutable());
$em->persist($accountstatement);
$em->flush();

My Stack versions:

Symfony : 6.4.9

PHP : 8.1.2-1ubuntu2.18

doctrine/dbal 4.0.4

doctrine/deprecations 1.1.3

doctrine/doctrine-bundle 2.12.0

doctrine/doctrine-fixtures-bundle 3.6.1

doctrine/doctrine-migrations-bundle 3.3.1

doctrine/event-manager 2.0.1

doctrine/inflector 2.0.10

doctrine/instantiator 2.0.0

doctrine/lexer 3.0.1

doctrine/migrations 3.8.0

doctrine/orm 3.2.1

mysql Ver 15.1 Distrib 10.6.18-MariaDB

There are a few questions on Stackoverflow with the similar issue but the root causes in those cases are different and hence doesn’t resolve my issue. Wonder if anyone can point out what could be wrong.

BIN number based discount in WooCommerce

I need to provide BIN number based discount in WooCommerce. I have tried to calculate discount and to apply coupon but none of it works while on the order-pay page. If i go back to checkout it applies the discount. I need this discount to be applied while on the order-pay.

Here is the AJAX POST


                                $.ajax({
                                    type: 'POST',
                                    dataType: 'json',
                                    url: ajaxUrl,
                                    data: {
                                        action: 'apply_coupon_based_on_card_number',
                                        coupon_code: '99vzm2fp' // or whatever
                                    },
                                    success: function(response) {
                                        console.log(response);
                                        if (response.success) {
                                            console.log('Coupon applied successfully:', response.data);

                                            $.ajax({
                                                type: 'POST',
                                                url: wc_checkout_params.ajax_url,
                                                data: {
                                                    action: 'update_order_review',
                                                    payment_method: paymentGateway
                                                },
                                                success: function(updateResponse) {
                                                    console.log('Order review updated successfully.');
                                                    $('.woocommerce-checkout-review-order-table').html(updateResponse.fragments['.woocommerce-checkout-review-order-table']);

                                                    // Append the updated order details
                                                    var orderDetails = `
                                                        <p>Order ID: ${response.data.order_id}</p>
                                                        <p>Subtotal: ${response.data.subtotal}</p>
                                                        <p>Discount: ${response.data.discount}</p>
                                                        <p>Shipping: ${response.data.shipping}</p>
                                                        <p>Total: ${response.data.total}</p>
                                                    `;
                                                    $('.order_details').append(orderDetails);
                                                },
                                                error: function(error) {
                                                    console.error('Error updating order review:', error);
                                                }
                                            });
                                        } else {
                                            console.log('Coupon not applied:', response.data.message);

                                            // Append the order details even if coupon not applied
                                            var orderDetails = `
                                                <p>Order ID: ${response.data.order_id}</p>
                                                <p>Subtotal: ${response.data.subtotal}</p>
                                                <p>Discount: ${response.data.discount}</p>
                                                <p>Shipping: ${response.data.shipping}</p>
                                                <p>Total: ${response.data.total}</p>
                                            `;
                                            $('.order_details').append(orderDetails);
                                        }
                                    },
                                    error: function(xhr, status, error) {
                                        console.error('Error applying coupon:', error);
                                        console.log('XHR:', xhr);
                                        console.log('Status:', status);
                                    }
                                });

and here is the PHP

function apply_coupon_based_on_card_number() {
    // Check if coupon is already applied
    if ( WC()->session->get( 'coupon_applied' ) ) {
        wp_send_json_error([
            'message' => 'Coupon already applied.',
            'order_id' => WC()->session->get('order_awaiting_payment'),
            'subtotal' => WC()->cart->get_subtotal(),
            'discount' => WC()->cart->get_cart_discount_total(),
            'shipping' => WC()->cart->get_shipping_total(),
            'total' => WC()->cart->total,
        ]);
    }

    // Get the coupon code from the request
    $coupon_code = isset($_POST['coupon_code']) ? sanitize_text_field($_POST['coupon_code']) : '';

    // Check if the coupon code exists and apply it
    if ( !empty($coupon_code) && WC()->cart->apply_coupon( $coupon_code ) ) {
        // Mark the coupon as applied in the session
        WC()->session->set( 'coupon_applied', true );

        // Send a success response with the updated cart details
        wp_send_json_success([
            'message' => 'Coupon applied successfully.',
            'order_id' => WC()->session->get('order_awaiting_payment'),
            'subtotal' => WC()->cart->get_subtotal(),
            'discount' => WC()->cart->get_cart_discount_total(),
            'shipping' => WC()->cart->get_shipping_total(),
            'total' => WC()->cart->total,
        ]);
    } else {
        // Send an error response if coupon application fails
        wp_send_json_error([
            'message' => 'Coupon could not be applied.',
            'order_id' => WC()->session->get('order_awaiting_payment'),
            'subtotal' => WC()->cart->get_subtotal(),
            'discount' => WC()->cart->get_cart_discount_total(),
            'shipping' => WC()->cart->get_shipping_total(),
            'total' => WC()->cart->total,
        ]);
    }

    wp_die();
}
add_action( 'wp_ajax_apply_coupon_based_on_card_number', 'apply_coupon_based_on_card_number' );
add_action( 'wp_ajax_nopriv_apply_coupon_based_on_card_number', 'apply_coupon_based_on_card_number' );

Like i said, tried calculating 10% discount also, could not apply it. I keep getting ‘Coupon already applied.’ message but nothing actually happens unless i go back to checkout where coupon shows and only then is applied.

Show alert if unavailable slot within the time range [closed]

As stated above, i would like to appear alert when unavailable slot query from SQL , below the code were not working .

$starttime = date("H:m:s", strtotime($_POST['start_time']));
$endtime = date("H:m:s", strtotime($_POST['end_time']));

function createOrder(){

  global $dbconnection;

  $date = $_POST['order_date'];
  $starttime = date("H:m:s", strtotime($_POST['start_time']));
  $endtime = date("H:m:s", strtotime($_POST['end_time']));
  $room = $_POST['room'];

  $dataQ = mysqli_query($dbconnection,"SELECT * FROM `booking`");

  $sql = "INSERT INTO `booking_slot`.`booking`(
      `name`,
      `department`,
      `order_date`,
      `start_time`,
      `end_time`,
      `room`,
      `purpose`)
      VALUES (
          '{$_POST['name']}',
          '{$_POST['department']}',
          '{$_POST['order_date']}',
          '{$_POST['start_time']}',
          '{$_POST['end_time']}',
          '{$_POST['room']}',
          '{$_POST['message']}')";
  ;

  while($row = mysqli_fetch_assoc($dataQ)){
      if($row['order_date'] == $date && ($row['start_time'] >= $starttime && $row['end_time'] <= $endtime) && $row['room'] == $room){
          echo '<script>';
          echo 'window.location.href="booking.php";';
          echo 'alert("someone is taken the slot, pls try again !");';
          echo '</script>;';
      }
       else {
               mysqli_query($dbconnection,$sql);
               header("Location: booking-completed.php");
           }
  }
  
}
?>

enter image description here

Expect if date, time range and room is matched show the alert , appreciate kind assistance on this , TQ !

Redirect in php Codex [duplicate]

Good morning. I have a problem with a plugin made on the codex php of wordpres, that contains a list of forms and a form field to update/insert a new one.

The readdress to the list page after an upsert operation doesn’t work The operation works perfectly on the database, but the readdressing to the form list page doesn’t work and always return this error:

Warning: Cannot modify header information – headers already sent by …” and then refers tp

…by (output started at C:MAMPhtdocswordpresswp-adminmenu-header.php:171) in C:MAMPhtdocswordpresswp-includespluggable.php on line 1435. This is the code :

<?php
   
function upsertTile(){

    ob_start();
    $id = null;
    if (isset($_GET['id'])) {
        $id = $_GET['id'];
    }
    
    $selected_id = isset($_GET['selected_id']) ? sanitize_text_field($_GET['selected_id']) : null;

    if ($selected_id) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'cf9';
        $selected_element = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $selected_id)
        );
    }

    if (isset($_POST['cf9_submit'])) {
        if (isset($_POST['cf9_nonce']) && 
            wp_verify_nonce($_POST['cf9_nonce'], 'cf9_form_submit')) {

            $name = sanitize_text_field($_POST['cf9_name']);
            $message = sanitize_textarea_field($_POST['cf9_message']);

            // Salva su database
            global $wpdb;
            $table_name = $wpdb->prefix . 'cf9';

            if ($id == null) {
                $wpdb->insert(
                    $table_name,
                    array(
                        'time' => current_time('mysql'),
                        'name' => $name,
                        'message' => $message
                    )
                );
            } else {
                $wpdb->update(
                    $table_name,
                    array(
                        'time' => current_time('mysql'),
                        'name' => $name ?? $selected_element->name,
                        'message' => $message ?? $selected_element->message,
                    ),
                    array(
                        'ID' => $id
                    )
                );
            }

            // Redirect to a different page
            wp_redirect(home_url(SLUG_PAGE), 302);
            ob_end_clean();
            exit;
        } else {
            echo '<p>Nonce verification failed.</p>';
        }

        if (isset($_GET['cf9_status']) && $_GET['cf9_status'] == 'success') {
            echo '<p>Thank you for your message!</p>';
        }
    }

    ob_end_flush(); // Invia l'output del buffer al browser e termina il buffering
}
?>

I tried to add “exit;” after each wp_redirect and add ob_start() and ob_end_flush() at the beginning and end of the method but it doesn’t work and it gives always the same problem.

I tried even to substitute wp_redirect with header(“Location :form-list.php”) but there’s no extra fat.

I simply expect to execute my upsert operation and to return to the home page of the plugin (form-list.php) , which has slug ‘c9-form-list’, and return a message (“Thank you for your message!” or in case “Nonce verification failed.” ).

Handling Nullable Numeric Inputs in Livewire Components

I’m working with Livewire components in a Laravel application, and I’m encountering issues when handling nullable numeric inputs (e.g., integers, floats). Specifically, when a user clears a numeric input field, Livewire assigns an empty string (“”) to the property. This behavior can lead to type errors if the property is type-hinted as a numeric type (int, float, etc.).

class MyComponent extends Component
{
    public ?int $numericValue = null;

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName, [
            'numericValue' => 'nullable|integer',
        ]);
    }

    public function render()
    {
        return view('livewire.my-component');
    }
}

When the numericValue input is cleared, Livewire assigns an empty string, resulting in a type error because ?int cannot be an empty string.

Cannot join mount namespace of pid 1: Operation not permitted

I have simple puppeteer script in nodejs like below

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch({
    headless: true,
    executablePath: "/snap/bin/chromium",
    args: ["--no-sandbox", "--disable-setuid-sandbox"],
  });

  const page = await browser.newPage();

  await page.goto("https://google.com");
  //get screenshot
  await page.screenshot({ path: "app4test.png" });
})();

when i ssh to my user and run node script.js , its working fine

When i do that via forever in ssh .. forever script.js , its working fine..

but when i do via php ,

<?php
// Define the command
$command = "forever start /home/example.com/app4test.js";

// Execute the command
$output = exec($command);

// Output the result
echo "<pre>$output</pre>";
?>

I get below error

(Use `node --trace-warnings ...` to show where the warning was created)
/home/example.com/node_modules/@puppeteer/browsers/lib/cjs/launch.js:310
                reject(new Error([
                       ^

Error: Failed to launch the browser process!
cannot join mount namespace of pid 1: Operation not permitted


TROUBLESHOOTING: https://pptr.dev/troubleshooting

    at Interface.onClose (/home/tradingtoolx.com/node_modules/@puppeteer/browsers/lib/cjs/launch.js:310:24)
    at Interface.emit (node:events:531:35)
    at Interface.close (node:internal/readline/interface:528:10)
    at Socket.onend (node:internal/readline/interface:254:10)
    at Socket.emit (node:events:531:35)
    at endReadableNT (node:internal/streams/readable:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Node.js v20.15.0
{"level":"error","message":"Forever detected script exited with code: 1"}

also when I do this via pm2 , i get the same above error from ssh as well as php script , I asked this to chatgpt , claude and gemini , none seems to help.I will open bounty soon as time starts as I wasted 2 days.Thank you.

Symfony app with doctrine: MariaDB to Postgres = column cannot be cast automatically to type jsonb

In the process of migrating from Mariadb to postgres 16 with these steps:

docker exec -ti app php bin/console doctrine:database:create
docker exec -ti app php bin/console make:migration
docker exec -ti app php bin/console doctrine:migrations:migrate 

docker run --rm -it --platform linux/amd64 --network app_network -v ./pgloader.load:/pgloader.load dimitri/pgloader:latest 
     pgloader pgloader.load

docker exec -ti app php bin/console doctrine:migrations:sync-metadata-storage

pgloader.load:

LOAD DATABASE
     FROM      mysql://root:root@database/dev
     INTO      pgsql://app:pass@postgres/dev

 WITH include drop, create tables

 ALTER SCHEMA 'dev' RENAME TO 'public';

I am getting into a stuck situation where my json migration is not working

php bin/console make:migration
generates

    #[ORMColumn(type: 'json', nullable: true, options: ["jsonb" => true])]
    private $emoji;

if I look into the migration file:

  $this->addSql('ALTER TABLE blog ALTER emoji TYPE JSONB');

If I connect to the DB and look at the schema it is of type text

now everything works BUT doctrine says that migration has not been executed

if I do

php bin/console doctrine:migrations:migrate 

I get

  SQLSTATE[42804]: Datatype mismatch: 7 ERROR:  column "emoji" cannot be cast automatically to type jsonb  
  HINT:  You might need to specify "USING emoji::jsonb".  

ubuntu apache default page appears on some devices

I have completed a server move of an application (ILIAS which is a learning management system). I have changed the A Record. The application is displayed normally on most end devices. On some, however, the standard default Ubuntu apache page is displayed. These are completely different devices. This are Can DNS caches or browser caches play a role here?

Standard function to clear Browser Caches but not working.
enter image description here

Trying to get data from Odoo using PHP/Laravel-9 using XMLRPC need help and guidance

I am able to authenticate but when trying to get data its giving me error

enter image description here

This is the error I am getting

Is there anyone who can help me to resolve this issue quickly please.

I am using Laravel version 9.46, check using via php artisan -v

<?php

namespace AppConsoleCommands;

use IlluminateConsoleCommand;
use PhpXmlRpcClient;
use PhpXmlRpcRequest;
use PhpXmlRpcValue;
use DB;

class FetchOdooData extends Command
{
    protected $signature = 'fetch:odoo-data';
    protected $description = 'Fetch data from Odoo and update local database';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Odoo credentials

        $url = 'http://urltoodoo::8049';
        $db = 'DBNAME';
        $username = 'username';
        $password = 'APIKEY';


        // Define XML-RPC endpoints
        $common_url = "{$url}/xmlrpc/2/common";
        $object_url = "{$url}/xmlrpc/2/object";

        // Create a client instance for common services
        $client = new Client($common_url);

        // Prepare the authentication request
        $request = new Request('authenticate', array(
            new Value($db, 'string'),
            new Value($username, 'string'),
            new Value($password, 'string'),
            new Value(array(), 'struct')
        ));

        // Send the authentication request
        $response = $client->send($request);

        //var_dump($response);

        if ($response->faultCode()) {
            $this->error('Error: ' . $response->faultString());
            return;
        }

        // Retrieve the user ID from the response
        $user_id = $response->value()->scalarval();

        if ($user_id) {
            $this->info("Authenticated successfully. User ID: $user_id");
        } else {
            $this->error("Authentication failed.");
            return;
        }

        // Function to call Odoo methods
        function callOdooMethod($client, $method, $params) {
            var_dump($method);
            var_dump($params);
            var_dump($client);
            
            $msg = new Request($method, array(new Value($params, 'array')));

            var_dump($msg);

            $resp = $client->send($msg);
            
            var_dump($resp);

            if ($resp->faultCode()) {
                return 'Error: ' . $resp->faultString();
            }
            return $resp->value();
        }

        // Fetch last sync time for a model
        function getLastSyncTime($model_name) {
            return DB::table('last_sync')->where('model_name', $model_name)->value('last_update');
        }

        // Update last sync time for a model
        function updateLastSyncTime($model_name) {
            DB::table('last_sync')->updateOrInsert(
                ['model_name' => $model_name],
                ['last_update' => now()]
            );
        }

        // Fetch data from Odoo
        function fetchData($models, $db, $user_id, $password, $model_name, $fields, $last_sync_time=0) {
            //$domain = $last_sync_time ? [['write_date', '>', $last_sync_time]] : [];
            $params = array(
                new Value($db, 'string'),
                new Value($user_id, 'int'),
                new Value($password, 'string'),
                new Value($model_name, 'string'),
                new Value('search_read', 'string'),
                new Value(array(
                    //new Value($domain, 'array'), // Domain filter
                    new Value($fields, 'array'), // Fields to retrieve
                ), 'array')
            );

            return callOdooMethod($models, 'execute_kw', $params);
        }

        // Update local database with fetched data
        function updateLocalDatabase($model_name, $data) {
            foreach ($data as $record) {

            }
        }

        // Create a client instance for object services
        $models = new Client($object_url);

        var_dump($models);

        // Define fields to retrieve for each model
        $project_fields = array('name', 'user_id', 'date_start', 'date_end', 'tasks');
        $task_fields = array('name', 'user_id', 'date_deadline', 'stage_id', 'description');
        $ticket_fields = array('name', 'stage_id', 'user_id', 'priority', 'description');
        $incident_fields = array('name', 'stage_id', 'user_id', 'priority', 'description'); // Replace with actual fields

        // Define models
        $models_to_fetch = array(
            'project.project' => $project_fields,
            'project.task' => $task_fields,
            'helpdesk.ticket' => $ticket_fields
        );

        /*,
            'your_incident_model_name' => $incident_fields // Replace with actual model name */

        foreach ($models_to_fetch as $model_name => $fields) {
            //$last_sync_time = getLastSyncTime($model_name);
            $data = fetchData($models, $db, $user_id, $password, $model_name, $fields); //, $last_sync_time

            if (is_string($data)) {
                $this->error("Error fetching $model_name: " . $data);
            } else {
                $this->info(ucfirst(str_replace('.', ' ', $model_name)) . " Data:n");
                print_r($data);
                updateLocalDatabase($model_name, $data);
                updateLastSyncTime($model_name);
            }
        }
    }
}

I am using “phpxmlrpc/phpxmlrpc”: “^4.10” package

Can anyone help me get authenticate and get the tickets and tasks data from odoo

Major IMAP services aren’t connecting to imap_open() in PHP

I’m at my wit’s end. When connecting to a major IMAP services in PHP, I get a “Connection refused” error. I don’t understand why this is happening.

I have tried iCloud (imap.mail.me.com), Yahoo! (imap.mail.yahoo.com), Gmail, (imap.gmail.com), Outlook (outlook.office365.com) and even Yandex to connect to my PHP script.

$email = '[email protected]';
$password = 'my app pass word';

$imap_host = '{imap.gmail.com:993/imap/ssl}INBOX'; //Gmail
$connection = imap_open($imap_host, $email, $password);

if ($connection === false) {
    die('Failed to connect to Gmail: ' . imap_last_error());
}

What am I doing wrong? However, using my domain’s IMAP works fine. Do they block IMAP connections?

P.S. The IMAP extension is installed. I am using shared web hosting with cPanel.

PHP valid url, including subdomains and also subpath

I need to check if a given string is valid. For me, the following and any other similar combinations are all valid URLs

'https://example.com/api/',
'https://www.example.com/test-subpath',
'https://www.example.com',
'example.com/test/page',
'www.example.com',
'www.subdomain.example.com',
'https://www.subdomain.example.com',
'subdomain.example.com',
'http://subdomain.example.com',
'https://subdomain.example.com'

while

'user-service/api/'

is invalid. I tried parse_url() and filter_var($url, FILTER_VALIDATE_URL) methods but non worked.

Thanks in advance.

Livewire Installation does not works

I have a blade application and i have installed livewire and published it
but when i use it in there artisan serve it works well but in the localhost (XAMPP) or in the host server
there are some errors in the console and livewire does not work

syntaxerror: unexpected token '>'

my application in

**D:/xampp/htdocs/**5dmaty/demo.elmofid.tech

my config/livewire.php asset_url

'asset_url' => '/5dmaty/demo.elmofid.tech/public/',

I’m expecting that there is an error in the recognizing of the root file.

I have tried some things

I have commanded
{{-- @livewireScrips --}}

And replaced it by

<script src="/5dmaty/demo.elmofid.tech/public/vendor/livewire/livewire.js" data-csrf="svtJBC64fw6FDa341rsniYXGsg2xXdWCY2Ta9t34" data-update-uri="/livewire/update" data-navigate-once="true"></script>

so it works well

so i have replaced the asset in the config/livewire.php

'asset_url' => '/5dmaty/demo.elmofid.tech/public/vendor',

but i returns does not work

and get a new error message in the console

http://localhost/5dmaty/demo.elmofid.tech/public/vendor/ net::ERR_ABORTED 403 (Forbidden)

so how to make this dynamic

Unable to print Laravel API data with Relationship in Vue Js

working with Laravel 10 API and Vue js 3 frontend

I have following EmployeeControll.php with 3 Models Employee,Title and Salary as well. Employee has many relationship with Salary and Title Models and Salary and Title Models has BelongsTo with Employee Model

<?php
namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsEmployee;
use AppModelsTitle;
use AppModelsSalary;

class EmployeeController extends Controller
{
    public function employees(){
        
            return response()->json(Employee::with('titles','salaries')->get(), 200);
    }
      
}

api.php

Route::get('employees', [AppHttpControllersEmployeeController::class, 'employees']);

and Vue js EmployeeList.vue is

<template>
    <div class="container">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">First Name</th>
                    <th scope="col">Last Name</th>
                    <th scope="col">Birth Date</th>
                    <th scope="col">Gender</th>
                    <th scope="col">Hire Date</th>
                </tr>
            </thead>

            <tbody v-for="employee in employees" :key="employee.emp_no">
                <tr class="table-secondary">
                    <th scope="row">{{ employee.emp_no }}</th>
                    <th scope="row">{{ employee.first_name }}</th>
                    <th scope="row">{{ employee.last_name }}</th>
                    <th scope="row">{{ employee.birth_date }}</th>
                    <th scope="row">{{ employee.gender }}</th>
                    <th scope="row">{{ employee.hire_date }}</th>
                   
                </tr>
            </tbody>
        </table>
        
    </div>
</template>

<script>
    import axios from 'axios';
    export default {
        name:'EmployeeList',
        data() {
            return {
                employees:Array
            }
        },
        created() {
            this.getEmployees();
        },
        methods:{
            async getEmployees() {
                let url = 'http://127.0.0.1:8000/api/employees';
                await axios.get(url).then(response => {
                    this.employees = response.data.employees;
                    console.log(this.employees);
                }).catch(error => {
                    console.log(error)
                });
            }
        
        
        },
        mounted() {
            console.log('Employee List Component Mounted');
        }
    }
</script>

above code segment did not display any data on vue js EmployeeList page. but web browser inspect uncounted Employee Array data with Relationship Models data? how could I fix above matter (displaying data on EmployeeList)

following EmployeeController showing result on EmployeeList.vue page

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsEmployee;
use AppModelsTitle;
use AppModelsSalary;

class EmployeeController extends Controller
{
    public function employees(){
        $employees = Employee::all();
        return response()->json(
            [
                'employees' => $employees,
                'message' => 'Employee',
                'code' => 200
            ]
            );
            
    }
       
}

but I need data with all relationship Models

PHP MySQL Prepared Statements, build the lists of the types for bind_param on fly

I am trying to find a simple way to construct the string to pass in the Prepared Statements in MySQLi especially the types ‘isiis’.

I already have an array that contains the arguments to pass to the query and by cycling through it I can build another array by checking if every single value in the array is a number, I use the is_numeric() function, or not.

The problem is that by doing this the method that writes to the database, I use a class, crashes.

It does not crash if I instead build the array of types using the str_repeat() function and assigning all variables the value ‘s’.

Below is some code for understanding.

This is my $args array

Array
(
[0] => 1433
[1] => 2
[2] => 71
[3] => 0
[4] => hello
[5] => pippo
[6] => 1
[7] => 1
[8] => 1
[9] => 9
)

I just need to differentiate the numeric variables from the remainder so I do
something as…

$fields = array();

foreach ($args as $s) {

    if(is_numeric($s)){
        $fields[] = 'i';
        #echo "is numeric";
    }
    else{
        #echo "is other";
        $fields[] = 's';
    }

}

that return something as

echo '<pre>'; print_r($fields); echo '</pre>';


Array
(
    [0] => i
    [1] => i
    [2] => i
    [3] => i
    [4] => s
    [5] => s
    [6] => i
    [7] => i
    [8] => i
    [9] => i
)

now I retrieve data (‘iissi..etc,etc’) in two ways

$types = implode("", $fields);

$types2 = str_repeat('s',sizeof($args));


echo printf("function implode return %s type %s and has len  %s.", $types ,gettype($types), strlen($types));
echo "<br>";
echo printf("function str_repeat return %s type %s has len  %s.", $types2 ,gettype($types2), strlen($types2));

The first method, using the implode() function doesn’t work and return:

function implode return iiiissiiii type string and has len 10.63

The second method using the str_repeat() function work and return:

function str_repeat return ssssssssss type string has len 10.62

By the way I noticed that the length of the two strings is not an integer,
it should be 10 and it is also slightly different.

This is my warning.

Warning: mysqli::prepare(): Couldn’t fetch mysqli in /var/www/html/virtualab/engine/dbms.php on line 90

Fatal error: Uncaught Error: Call to a member function bind_param() on bool

Do you have any suggestions, what am I missing?

Thanks for your attention and sorry for the horrible code writing…