Your Location is: Home > Php

PHP: foreach insert into, a exploded-list

From: Hanoi View: 3791 babawo 
 php

Question

Everything seems correct, but nothing happens. I want to INSERT a PHP exploded keyword list. into the new table, (already working/ OK): product_keywords

product_id     keyword

from my old table PRODUCTS,

product_id     keywords (a comma-list)

Where is the error(?)

explode echo TEST (already working/ OK)

$teile_arr = explode(",", $stringx);

foreach($teile_arr as $keyword){
echo " ID: ".$res_id[$i]."<br>";
echo "KW: ".$keyword."<br>";
}

html echo TEST result OK:

KW: Christmas
ID: 544405
KW: tree
ID: 544405
KW: Santa
ID: 544405

display input echo (already working/ OK)

foreach($teile_arr as $keyword){
echo "<input type='text' name='keyword".$res_id[$i]."' value='".$keyword."'>";
}

not working, table is still empty PHP does not insert any content in the database. There must be a problem with "foreach" at this point.

foreach($teile_arr as $keyword){
$sql="INSERT IGNORE INTO product_keywords SET product_id='".$res_id[$i]."', keyword='".$keyword."";
$db->execute($sql);
}

Best answer

Insert statements use VALUES, update statements use SET.

"INSERT IGNORE INTO product_keywords SET product_id='".$res_id[$i]."', keyword='".$keyword."";

Should be

"INSERT IGNORE INTO product_keywords(product_id,keyword) VALUES ('{$res_id[$i]}', '{$keyword}')";

Also, you should be using prepared statements to protect from sql injection attacks.

How can I prevent SQL injection in PHP?