我已经通过ajax post将数组从jquery传递到php处理脚本。我注意到我在php中的foreach迭代没有做任何事情。我添加了一个vat_dump,并意识到我为这个数组得到了奇怪的结果。为什么会在值中附加字符串(x)?我相信这就是我的循环运行不正常的原因。
我对php中的数组非常熟悉,但就将jquery传递给php并使用它们而言,我从来没有遇到类似这样的事情。
$('#delete').on('click', function () {
var selected = [0, 1, 2, 3, 4, 5];
var data = {
'selected': selected
};
$.ajax({
type: 'post',
url: '/process/p_delete.php',
data: data,
dataType : 'json'
}).done(function (response) {
if (response.success)
{
// show success toast
toastr.info('Selected activities have been deleted from your account.');
}
else
{
// show error toast
toastr.error('An error has occurred. Please contact support.', 'Error');
}
});
});
然后在php:
$selected = $_POST['selected'];
var_dump($selected);
// prepare the statement
$stmt = $db->prepare("DELETE FROM logs WHERE activity_id = ? AND account_id = ?");
//loop through array and delete each selected
foreach($selected as $key)
{
$binding = array(
'account_id' => $_SESSION['user']['account_id'],
'activity_id' => $key
);
// execute the delete
$stmt->execute($binding);
}
转储结果如下:
array(6) {
[0]=>
string(1) "0"
[1]=>
string(1) "1"
[2]=>
string(1) "2"
[3]=>
string(1) "3"
[4]=>
string(1) "4"
[5]=>
string(1) "5"
}
答案 0 :(得分:0)
尝试
$stmt->execute(array($key, $_SESSION['user']['account_id']));
或使用命名参数(参见http://php.net/manual/en/pdostatement.execute.php)。而不是进行多次查询,最好只使用一个查询使用WHERE IN -clause。
答案 1 :(得分:0)
我不是PHP的专家,但我会尝试这样:
<强> JAVASCRIPT 强>
var selected = [0, 1, 2, 3, 4, 5];
var jsonObj = JSON.stringify(selected);//encode array to JSON format
var data = {
'selected': jsonObj
};
<强> PHP 强>
$data = json_decode(stripslashes($_POST['selected']));//decode json to array
foreach($data as $value){
echo $value;
}
答案 2 :(得分:0)
试试这个
$sth = $dbh->prepare('DELETE FROM logs WHERE activity_id = :activityId AND account_id = :accountId');
//loop through array and delete each selected
foreach($selected as $key)
{
$sth->bindParam(':activityId', $_SESSION['user']['account_id'], PDO::PARAM_INT);
$sth->bindParam(':accountId', $key, PDO::PARAM_INT);
$sth->execute();
}
如果你得到$_SESSION['user']['account_id']
和$key
,那么它就可以了。还检查pdo数据库连接和列名和表名
答案 3 :(得分:0)
doh ...我想这就是我累得太累了......
$stmt = $db->prepare("DELETE FROM logs WHERE activity_id = :activity_id AND account_id = :account_id");
我从我的代码的另一部分复制了我的语句,我直接将值插入到此语句中。在这一个我绑定他们...因此,=?在这种情况下并不好。