Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an array into a single MySQL Prepared statement w/ PHP and PDO

Tags:

loops

php

mysql

pdo

During an online enrollment, a customer may select a number of programs which they choose to enroll for. These programs are three digit integers and are stored in an array.

For example:

I want to enroll in programid 155, 165, 175, and 185.

My array is set up as simple as:

$data = array();

$data[] = 155;

$data[] = 165;

$data[] = 175;

$data[] = 185;

When it comes time to insert this information into the associated table, I also include additional elements from the other part of the enrollment:

For example, if I were doing a SINGLE program insert statement, it would look as follows:

$stmt = $db->prepare("INSERT INTO table SET memberID=?, programID=?, date_added=NOW()");
$stmt->execute(array($memberid, 155));

I would normally create a simple loop for the array above which would call multiple instances of the sql statement and execute such as:

for($j = 0; $j < (count($data)-1); $j++) {
   $stmt = $db->prepare("INSERT INTO table SET memberID=?, programID=?, date_added=NOW()");
   $stmt->execute(array($memberid, $data[$j]));
}

I do realize the code above is invalid ( $data[$j] ) but looking for the right way to do the call.

I have also been told before that building a single dynamic sql statement is overall better than multiple calls like above. My first pass would be something like:

$sql = array(); 
foreach( $data as $row ) {
    $sql[] = '("'.$memberid.'", "'.$row[$j].'", NOW()")';
}
mysql_real_query('INSERT INTO table (memberid, programid) VALUES '.implode(',', $sql));

but with PDO I am not quite sure how this works, especially with placeholders (?).

Any suggestions?

like image 989
JM4 Avatar asked Jan 07 '11 18:01

JM4


People also ask

How do I add an array to a single column in MySQL?

$data = array("one", "two", "tree"); // output one, two, three $insert_data = implode(",", $data); or $insert_data = json_encode($data); Thats for inserting data in single column. While retrieving you can do explode() or json_decode() to get the return data and can use them in the multi-select again.

Which method is used for PHP MySQL insert data using PDO?

PHP Code to INSERT Data Into MySQL Database. There are two methods you can use to INSERT data into your MySQL database. The PHP MySQLi method and PHP Data Object or PDO method.

Can I use PDO with MySQL?

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.

Can I insert array in MySQL?

You can not insert an array directly to MySQL as MySQL doesn't understand PHP data types. MySQL only understands SQL. So to insert an array into a MySQL database you have to convert it to a SQL statement. This can be done manually or by a library.


2 Answers

You could build the query programatically...:

$sql = 'INSERT INTO table (memberID, programID) VALUES ';
$insertQuery = array();
$insertData = array();
foreach ($data as $row) {
    $insertQuery[] = '(?, ?)';
    $insertData[] = $memberid;
    $insertData[] = $row;
}

if (!empty($insertQuery)) {
    $sql .= implode(', ', $insertQuery);
    $stmt = $db->prepare($sql);
    $stmt->execute($insertData);
}
like image 83
ircmaxell Avatar answered Sep 24 '22 18:09

ircmaxell


2 solutions

// multiple queries
$stmt = $pdo->prepare('INSERT INTO table SET memberID=:memberID, programID=:programID, date_added=NOW()');
$data = array(155, 165, 175, 185);
foreach($data as $d) {
    $stmt->execute(array(':memberID' => $memberid, ':programID' => $d));
}

And

// one query
$data = array(155, 165, 175, 185);
$values = array();
foreach($data as $d) {
    $values[] = sprintf('(%d, %d, NOW())', $d, $memberid);
}
$sql = sprintf('INSERT INTO table (memberID, programID, date_added) VALUES %s', implode (', ', $values));
$pdo->exec($sql);
like image 32
Xavier Barbosa Avatar answered Sep 20 '22 18:09

Xavier Barbosa