TransWikia.com

Wordpress, Error when trying to insert data >> Notice: wpdb::prepare was called incorrectly

WordPress Development Asked on November 28, 2021

I have the following code to insert multiple rows into my custom WordPress table.

When I run the form to submit the data and insert it to the WordPress database I get the this error message:

Notice: wpdb::prepare was called incorrectly. Unsupported value type
(array).
and
Warning: mysqli_real_escape_string() expects parameter 2 to be string,

    global $wpdb;
    $values = array();
    $place_holders = array();

    $query = "INSERT INTO wp_1com_dc_attedance (customer_id, location_id, funding_source, attend_date, approval_date, attend_am, attend_pm) VALUES";

    foreach($_POST as $key => $value)
    {
         array_push($values, $value);
         $place_holders[] = "('%s', '%s', '%s', '%s', '%s', '%s', '%s')";
    }

    $query .= implode(', ', $place_holders);
    $wpdb->query( $wpdb->prepare("$query", $values));

The array I am passing to the code in the $_POST is as follows:

Array ( 
[customer_id] => Array ( [0] => 2 [1] => 4 ) 
[locations_id] => Array ( [0] => 1 [1] => 1 ) 
[funding_source] => Array ( [0] => 1 [1] => 2 ) 
[attend_date] => Array ( [0] => 2018-02-09 [1] => 2018-02-09 ) 
[approval_date] => Array ( [0] => 2018-02-08 [1] => 2018-02-08 ) 
[attend_am] => Array ( [0] => 1 ) 
[attend_pm] => Array ( [0] => 1 )  
) 

I hope somebody can help me as I have been working to try and fix this for the best part of today.

One Answer

I have fixed this, the issue was in the way I was creating the array. I was using a multi-dimensional and needed to call the correct level of the array in the post.

By calling

$_POST['customer']

which was the name of the array I could access the correct rows. Here is what the array looks like. Quite painful but I solved it in the end so wanted to ensure I shared for others.

Array ( 
[customer] => Array ( 
    [0] => Array ( [customer_id] => 6 [locations_id] => 1 [funding_source] => 2 [attend_date] => 2018-02-12 [approval_date] => 2018-02-12 ) 
    [1] => Array ( [customer_id] => 2 [locations_id] => 1 [funding_source] => 1 [attend_date] => 2018-02-12 [approval_date] => 2018-02-12 ) 
) 
[approve_data] => Approve Attendance )

Answered by Julian on November 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP