mysqli预处理语句其中var = var dynamic

时间:2015-02-26 03:14:09

标签: php mysql mysqli prepared-statement

如果我有如下准备声明:

  

$ stmt = $ mysqli-> prepare(“SELECT fielda,fieldb,fieldc,from tablea where $ option =?”)

是否也可以准备$option变量?

注意:$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>

,另一个字段来自一个简单的输入文本框。该字段将填写准备好的声明中的?

3 个答案:

答案 0 :(得分:0)

你可以使用方法&#34; bindParam&#34;

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");  
$stmt->bindParam(1, $name); $stmt->bindParam(2, $value);

答案 1 :(得分:0)

您无法绑定表或列,因为prepare会自动转义它们并导致语法问题。此外,在准备这样的时候,建议不要在查询中使用变量,因为你绕过了绑定过程,这基本上违背了准备的目的。只需确保验证/清理文本输入。有很多选择,这里有一些。

选项#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();

选项#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";
}

答案 2 :(得分:0)

最简单的方法:

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");  
$stmt->execute(array($_REQUEST['name'],$_REQUEST['value']));

但这不安全

我建议使用:

// Read values to $name and $value
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");  
$stmt->execute(array($name,$value));

根据您的要求:

// if there is a value in $option
$stmt = $dbh->prepare("SELECT fielda, fieldb, fieldc, from tablea where $option = ?" );
$stmt->execute(array($option));