Use Arrays in PHP's PDO

Hi,

My app’s DataGrid gives me an array of selected IDs like this

{10, 25, 7, 89, 100}

this is the customer_id which is :param_id in PDO

How can I pass it to be used in MySQL for:

INSERT INTO selected (selected_customer) VALUES (param_id)

so each will be saved individually…

Thanks,
Jassim

Something like this?

$array = array(10, 25, 7, 89, 100) ; // This is your array of IDs

$sql = $db->prepare("INSERT INTO selected (selected_customer) VALUES (:param_id)") ; // Prepare the INSERT

foreach($array as $id) {   // Iterate through the array
    $sql->execute([':param_id' => $id) ;   // Execute for each ID
}

but won’t this send too many requests on the network? especially if I have 5,000 customers (increasing)?

I don’t know the context in which this will be used. I counted only 5 ID values in your example. Will thousands be inserted in one run of the script?

You can make multiple inserts in a single query:-

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of comma-separated column values, with lists enclosed within parentheses and separated by commas. Example:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
https://dev.mysql.com/doc/refman/5.5/en/insert.html

1 Like

How about sending the array as a string param_customers and do the rest in MySQL?

Does MySQL knows how to deal with arrays and put it into individual INSERT statements?

No, that’s what PHP is for

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.