php - MySQLi query to loop through array and update multiple rows -


i have array like:

$postdata[1] = 'this'; $postdata[2] = 'that'; $postdata[3] = 'the other'; 

and want loop through array , update of rows id corresponds array key. like:

foreach ($postdata $key => $value) {   if ($key == 1) {     $update = $db->query("update site_email_templates set content='$postdata[1]' id = 1");   } else if ($key == 2) {     $update = $db->query("update site_email_templates set content='$postdata[2]' id = 2");   } else if ($key == 3) {     $update = $db->query("update site_email_templates set content='$postdata[3]' id = 3");   } } 

what simplest way this, not particularly knowing how many array keys there are, , keeping in 1 query?

my first answer accepted op, have updated answer since 1 thinks previous answer might exposed sql-injection.

the code below tested on real environment , served prepared statement preventing sql-injection:

$sql = "update `site_email_templates` set `content` = (:content) `id` = (:id)"; $stmt = $dbconn->prepare($sql); foreach ($postdata $id => $content) {     $stmt->execute([':id' => $id, ':content' => $content]); } 

for more details sql injection can read more:
https://www.owasp.org/index.php/sql_injection


first answer long time ago
this:

for ($i = 1; $i < count($postdata); $i++)     $update = $db->query("update site_email_templates set content=" . $postdata[$i] . "      id =" . $i); 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -