0

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.

1
  • I think the issue is in the way you build the $query (specifically in the second line of your foreachloop). Each element of the $place_holders array is what you should append to $query, but you are appending it as many times as there are keys in your $_POST array. This comment section is not long enough to elaborate and dump an example, but if you try to echo your $query I think the issue sould become quite clear :)
    – Iceable
    Feb 9, 2018 at 18:02

1 Answer 1

1

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 )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.