MySQLi准备语句和提取字段

时间:2017-08-16 16:18:55

标签: php mysqli prepared-statement

我有一个名为$lines的字符串数组,我想用每个字符串搜索数据库。

我的工作原理是什么:

foreach($lines as $line) {
    $line = real_escape_string($line);
    $sql = "select * from $table where $column like '%$line%'"
    $result = $conn->query($sql);
    if($result->num_rows) {
        while ($row = $result->fetch_assoc())
            //Name and Date are are only 2 out of 15+ column names from the db table
            echo "<tr><td> {$row['Name']} </td>
                  <td>     {$row['Date']} </td></tr>"; 
    }

但是,我不想要这个。我想使用预准备语句,并能够使用上面的列名。我尝试过的:(来自here

$vars = array();
$data = array();
$stmt = $conn->prepare("SELECT * FROM $table WHERE `$column` LIKE '%?%'");
$stmt->bind_param("s", $line);
$stmt->execute();
$result = $stmt->store_result();
$meta = $result->result_metadata();

echo "WORKS"; //doesn't print
while ($field = $meta->fetch_field())
    $vars[] = &$data[$field->name];
call_user_func_array(array($result, 'bind_result'), $vars);
$i = 0;
while ($result->fetch())  {
    $array[$i] = array();
        foreach ($data as $k=>$v)
            $array[$i][$k] = $v;
        $i++;
}
print_r($array);

1 个答案:

答案 0 :(得分:1)

由于使用预准备语句绕过了对引号的需要并传递了确切变量,因此需要在变量中传递通配符,而不是在查询中:

$stmt = $conn->prepare("SELECT * FROM $table WHERE `$column` LIKE ?");
$stmt->bind_param("s", '%'.$line.'%');