I am trying to insert many rows(6) in a table with a prepared statement.
here is the syntax(only 2 rows insertions…for clarity)
if($stmt=$connection->prepare('INSERT INTO store_open (b_user_ID,open_time,close_time,day)
VALUES(?,?,?,?),(?,?,?,?)'))
Despite the INSERT syntax for inserting many rows in a table is the above…I do not think this will with a prepared statement…cause when I am going to use bind_param…which variable is going to be associated with what question mark symbol…I hope you understand what I mean.
What might be the solution to it…a for loop?
Since I am going to be inserting 6 rows at a time…that means making 6 INSERTs…something not so efficient I think…
I made a calendar with the ability to make appointments on any given day and developed this as a way of entering 7-8 rows of time. It’s a crazy way of doing it, but it does use prepared statements:
It uses PDO and is written in OOP fashion, but I don’t think it would be to hard to convert to either procedural or mysqli? I know I converted this from procedural to OOP.
the only problem in my case is that the data I want to insert to the database are contained in a multidimensional array and it is a little hard looping through it.
I will try to be more specific about the array…
It is actually the weekdays(7 array members)…and its day holds two other array members…these are 2 24H times…it could be 14:00:00 and 17:00:00 for example.
In essence the array holds info about the schedule(open/close time) of a store…
Here is the code so far:
if($stmt=$connection->prepare('INSERT INTO store_open (b_user_ID,open_time,close_time,day)VALUES(?,?,?,?)'))
foreach ($content as $key => $value) {
$stmt->bind_param('isss',$b_user,$key);
$stmt->execute();
}
b_user_ID is not contained in the array…there is no problem with it…
As you can understand from the above the array that holds the weekdays is $content
Here is an example of a bulk-insert usisng prepared statements. It uses PDO but it shouldn’t be very hard to convert to mysqli: (yes I know I need to add more validation to my own code)
try {
$sql="
INSERT INTO
ue_conversation_participant
(
conversation
, user
, deleted
, unread
)
VALUES
";
$insertQuery = array();
$insertData = array();
foreach ( $new_recipient_ids AS $new_recipient_id ) {
$insertQuery[] = '(?,?,?,?)';
$insertData[] = $_POST['pm_id'];
$insertData[] = $new_recipient_id['id'];
$insertData[] = 0;
$insertData[] = 1;
}
if (!empty($insertQuery)) {
$sql .= implode(', ', $insertQuery);
$stmt = $this->db->prepare($sql);
$stmt->execute($insertData);
}
}
catch (PDOException $e) {
$this->db->rollBack();
error_log('Error reading the session data table in the session reading method.');
error_log(' Query with error: '.$sql);
error_log(' Reason given:'.$e->getMessage()."\n");
return false;
}
}
The above example is used to insert as many participants as needed to a conversation in a PM system. The rollback is there because it’s forming part of a transaction