【发布时间】:2015-02-10 06:30:09
【问题描述】:
我有这个数组 JSON POST 请求到一个 PHP 文件。
Array
(
[user_id] => 1
[date] => 2014-12-05
[time] => 12:00
[description] => lol
[friends] => "12","9"
[PHPSESSID] => 5ae7c3e6339c528e7804020dd0f0cdbb
)
我尝试使用单个 sql 查询将值 (12 | 1) 和 (9 | 1) 添加到 mysql 表中
表:
u_id | f_id
1 | 12
1 | 9
到目前为止我所拥有的:
$friendarray = $_POST['Friends'];
foreach( $friends as $friendsarray ) {
$values[] = "(" . $u_id . "," . $friendsarray . ")";
}
$query = "INSERT INTO up2_friends_to_users (u_id , f_id ) VALUES ".implode(',',$values);
$stmt = $db->prepare($query);
$result = $stmt->execute();
如您所见,这根本不起作用。我试图实现这样的目标:
$query_params = array(
':u_id' => $_POST['user_id'],
':f_id' => $friendid,
然后想这样发送:
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
是否可以像这样创建具有多行的单个查询?
感谢 RobP 的回答:
$friendsarray = explode(',',$_POST['friends']);
$placeholders = [];
for($i=0, $len=count($friendsarray); $i < $len; $i++) {
$placeholders[i] .= "(:u_id".$i.", :f_id".$i.")"; // entries like "(:u_id0, :f_id0)"
}
$query = "INSERT INTO up2_friends_to_users (u_id , f_id ) VALUES ".implode(",", $placeholders);
$stmt = $db->prepare($query);
for($i=0, $len=count($placeholders); $i < $len; $i++) {
$stmt->bindParam(':u_id'.$i, $_POST['user_id']);
$nextFriend = $friendsarray[$i];
$stmt->bindParam(':f_id'.$i,trim($nextFriend,'"'));
}
$result = $stmt->execute();
现在 f_id 始终为空。
【问题讨论】:
-
分配
$query时需要先设置$values再使用。 -
您指定
$friendarray,但在foreach循环中使用$friends。 -
挑战是使用长的 VALUES 列表执行单个 INSERT,但仍将所有这些值作为注入安全的绑定参数。我在下面戳了一下。