I am using following code to insert multiple records into a table. As you can see the query is in a loop. Every time the loop executes, seperate sql query is run to insert it.
I want a approach where instead of running multiple queries, only single INSERT sql query should run with multiple insert statements.
Though this code of mine is functioning perfectly but I need to optimize it.
$managed_ailments = unserialize($ailments);
foreach($managed_ailments as $ailment_id)
{
$sql = "INSERT INTO ". TABLE_PATIENTS_AILMENTS_RECORDS ."";
$sql .= "(patient_id, ailment_id, datecreated) VALUES";
$sql .= "($patient_id, $ailment_id, now())";
$query = $mysql->query($sql);
}
Here $managed_ailments is a serialized array which i have unserialized. There can be one or more than one values in the array. $mysql->query($sql) is my custom function.
Please help me to convert this code into a single sql query which does it all.
Thanks in advance.
Something like this should work:
$managed_ailments = unserialize($ailments);
$sql = "INSERT INTO ". TABLE_PATIENTS_AILMENTS_RECORDS ."";
$sql .= "(patient_id, ailment_id, datecreated) VALUES (";
$query_parts = array();
foreach($managed_ailments as $ailment_id) {
$query_parts[] = "($patient_id, $ailment_id, now()";
}
$sql .= implode(",", $query_parts);
$sql .= ")";
$query = $mysql->query($sql);
you can add a value statement for each recordthen exectute the query, ie:
INSERT INTO example
(example_id, name, value, other_value)
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
You can use MySQLi extension which has prepared statement. You will send the template once to the server then withen a loop you just send data.
//initialize and connect $mysqli via MySQLi extension
$sql = "INSERT INTO ". TABLE_PATIENTS_AILMENTS_RECORDS ."";
$sql .= "(patient_id, ailment_id, datecreated) VALUES";
$sql .= "(?, ?, now())";
$stmt = $mysqli->prepare($query)
$managed_ailments = unserialize($ailments);
foreach($managed_ailments as $ailment_id) {
$stmt->bind_param("ii", $patient_id, $ailment_id);
$stmt->execute();
}
Note that I'm assuming both $patient_id, $ailment_id are integers. And also assuming you don't want to keep the results of executed queries, because you are overwriting the $query
This will reduce the overhead of NOW() function and save some bandwidth.
Here is a link to PHP MySQLi Documentation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.