我被告知“没有办法使用预处理语句将数组绑定到SQL语句”,但我已经完成了。我很难重新创建它。
我有一条更新数据库的声明:
if (isset($_POST['printRow'])){
$ids = "";
foreach ($_POST['checkbox'] as $rowid)
{
if(!empty($ids)) $ids .= ',';
$ids .= $rowid;
$_SESSION['ids'] = $ids;
}
}
我在这里忘记发布WORKING代码:
$stmt = $conn->prepare("UPDATE just_ink SET deleted=1 WHERE ID IN( " . $ids . ")");
$stmt->execute();
但我仍有以下问题:
其中$ id可以是一个或多个id。
所以这就是问题所在,如果我尝试使用$ ID并设置一个SESSION
($_SESSION['ids'] = $ids;)
用于其他页面。
在下一页我想用$ _SESSION ['ids']选择数据,所以,
$stmt = $conn->prepare("SELECT * FROM just_ink WHERE ID IN( " . $_SESSION['ids'] . ")");
$stmt->execute();
但这不起作用。有什么想法吗?
答案 0 :(得分:0)
它不起作用,因为正如您所说的那样,您无法使用预准备语句将数组绑定到SQL语句。
绑定数组的正确方法是创建一个占位符字符串(问号),然后在循环中绑定params。
我们假设您有一系列必需的ID
被称为$checkboxes
。首先,我们需要创建一个字符串,我们将在查询中使用它来绑定所需的参数。如果$checkboxes
有3个项目,我们的字符串将显示为
$placeholder = "?,?,?";
为此,我们可以使用str_repeat函数创建一个字符串,其中除了最后一个元素之外,每个元素都会将?,
部分添加到占位符。对于最后一个元素,我们需要连接单个问号。
$placeholder = str_repeat('?,', count($checkboxes)-1).'?';
现在我们需要形成并准备一个包含占位符的查询:
$query = 'SELECT * FROM just_ink WHERE ID IN (".$placeholder.")';
$stmt = $conn->prepare($query);
要将每个ID
绑定到其占位符,我们在循环中使用bindParam方法:
for ($i=0; $i<count($checkboxes); $i++) {
$stmt->bindParam($i+1, ($checkboxes[$i]); #position is 1-indexed
}
$stmt->execute();
答案 1 :(得分:0)
您可以使用call_user_func_array
将数组与mysqli预处理语句一起使用您的代码最终会像这样
$varArray = array();
$questionArray = array();
foreach ($_POST['checkbox'] as $daNumber=>$daValue) {
$questionArray[] = "?";
//We're declaring these as strings, if they were ints, they would be i
$varArray[0] .= 's';
//These must be relational variables. The ampersand is vry important.
$varArray[] = &$_POST['checkbox'][$daNumber];
}
//comma separated series of questionmarks
$allDaQuestions = implode(', ', $questionArray);
$query = "SELECT * FROM just_ink WHERE ID IN ($allDaQuestions)";
$stmt = $conn->prepare($query);
//Where the magic happens
call_user_func_array(array(&$stmt, 'bind_param'), $varArray);
//continue with your regularly scheduled broadcast
$stmt->execute();
//etc.
答案 2 :(得分:-1)
你在文件的开头设置了session_start()吗?如果不先使用$ _SESSION,则不能使用$ _SESSION