Florin C.
Florin C.

Reputation: 366

PHP MySQL insert array syntax

I have a form where I input 2 values: sku and filter_id. I then take sku and retrieve from DB an array of product_id that correspond that sku. For each product_id I need to insert a query back into DB with 2 values: product_id and filter_id.

I would like to build the query in the foreach loop and run a single SQL query at the end for efficient use of resources.

Here is my PHP code:

// Escape user inputs for security
$sku = mysqli_real_escape_string($db, $_POST['sku']);
$filter_id = mysqli_real_escape_string($db, $_POST['filter_id']);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
} 

//get product_id array for requested sku
$sql = "SELECT product_id FROM oc_product WHERE sku = '$sku'";
$product_id_array = $db->query($sql);

if ($product_id_array->num_rows > 0) {
    foreach( $product_id_array as $row ) {
    $query_row[] = "('$row['product_id']','$filter_id')";
    }

    $final_query = "INSERT IGNORE INTO oc_product_filter (product_id, filter_id) VALUES " .implode(',', $query_row);
    $db->query($final_query);
} else {
    echo "no products found.";
}

Current error is:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

That is for this line: $query_row[] = "('$row['product_id']','$filter_id')";

Can anyone help me with the correct syntax to use? Thank you!

Upvotes: 0

Views: 138

Answers (2)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Update your code

$query_row[] = "('$row['product_id']','$filter_id')";
                 ^^                 ^^

into

$query_row[] = "('{$row['product_id']}','$filter_id')";
                 ^^                  ^^

You need to enclose your array variables within {}

Upvotes: 2

Happy Coding
Happy Coding

Reputation: 2525

Change from

$query_row[] = "('$row['product_id']','$filter_id')";

to

 $query_row[] = "('".$row['product_id']."','".$filter_id."')";

Upvotes: 0

Related Questions