[英]mysqli prepared statement where var = var dynamic
If I have a prepared statement as follows: 如果我有如下准备声明:
$stmt = $mysqli->prepare( "SELECT fielda, fieldb, fieldc, from tablea where $option = ?" )
$ stmt = $ mysqli-> prepare(“SELECT fielda,fieldb,fieldc,from tablea where $ option =?”)
Is it possible to prepare the $option
variable as well? 是否可以准备
$option
变量?
Note: the $option
variable comes from a drop down list as follows 注意:
$option
变量来自下拉列表,如下所示
<select name="option">
<option value="blah1">blah1</option>
<option value="blah2">blah2</option>
<option value="blah3">blah3</option>
<option value="blah4">blah4</option>
</select>
and the other field comes from a simple input text box. 另一个字段来自一个简单的输入文本框。 This field will fill up the
?
这个字段会填满
?
in the prepared statement. 在准备好的声明中。
you can use method "bindParam" 你可以使用方法“bindParam”
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name); $stmt->bindParam(2, $value);
You can't bind tables or columns because prepare escapes them automatically and will cause a syntax issue. 您无法绑定表或列,因为prepare会自动转义它们并导致语法问题。 Also, when preparing like this it's advisable not to use a variable in the query because you're bypassing the binding process which basically defeats the purpose of preparing.
此外,在准备这样的时候,建议不要在查询中使用变量,因为你绕过了绑定过程,这基本上违背了准备的目的。 Just make sure to validate/sanitize your text input.
只需确保验证/清理文本输入。 There are a lot of options, here are a few.
有很多选择,这里有一些。
Option #1: 选项1:
switch ($option) {
case "blah1":
$query = "SELECT fielda, fieldb, fieldc, from tablea where blah1=?";
break;
case "blah2":
$query = "SELECT fielda, fieldb, fieldc, from tablea where blah2=?";
break;
case "blah3":
$query = "SELECT fielda, fieldb, fieldc, from tablea where blah3=?";
break;
}
$stmt = $mysqli->prepare($query);
$stmt->bindParam('s', $input);
$stmt->execute();
$stmt->close();
Option #2: 选项#2:
$whitelist = ["blah1","blah2","blah3"];
If (in_array($option, $whitelist)) { //at this point variable is safe to use//
$stmt = $mysqli->prepare("SELECT fielda, fieldb, fieldc, from tablea where $option=?");
$stmt->bindParam('s', $input);
$stmt->execute();
$stmt->close();
} else {
echo "unexpected value";
}
The simplest way: 最简单的方法:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->execute(array($_REQUEST['name'],$_REQUEST['value']));
But this is not secure ! 但这不安全 !
I suggest to use: 我建议使用:
// Read values to $name and $value
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->execute(array($name,$value));
For your requirement: 根据您的要求:
// if there is a value in $option
$stmt = $dbh->prepare("SELECT fielda, fieldb, fieldc, from tablea where $option = ?" );
$stmt->execute(array($option));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.