我有一个数组:
var arr = [{"title": "lorem", "desc": "ipsum"}, ...];
我尝试通过AJAX保存到数据库:
$.post("sample.php", {arr: arr}, function(data) { ... });
使用以下代码:
$data = $_POST['arr']
$values = array();
foreach($data as $value)
{
$values[] = '('. $value['title'] .', '. $value['desc'] .')';
}
$sql = "INSERT INTO locations (title, desc)
VALUES " . implode( ',', $values );
它给了我以下错误:
Invalid argument supplied for foreach()
我不是一个真正的PHP开发者,所以我不明白出了什么问题。有什么想法吗?
答案 0 :(得分:0)
您应该为每个值执行插入 你应该检查帖子内容
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
}
}