I have an array:
var arr = [{"title": "lorem", "desc": "ipsum"}, ...];
that I try to save to a database via AJAX:
$.post("sample.php", {arr: arr}, function(data) { ... });
with the following code:
$data = $_POST['arr']
$values = array();
foreach($data as $value)
{
$values[] = '('. $value['title'] .', '. $value['desc'] .')';
}
$sql = "INSERT INTO locations (title, desc)
VALUES " . implode( ',', $values );
It gives me the following error:
Invalid argument supplied for foreach()
I am not really a PHP dev, so I don't understant what goes wrong. Any ideas?
You should perform the insert for each value
and you should check for the post content
if isset($_POST['arr']) {
foreach($data as $value)
{
$sql = "INSERT INTO locations (title, desc)
VALUES ( " . $value['title'] . ", " .$value['desc'] . " );"
// then exec you insert query -- depending by the db drivvers you are using
}
}
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.