从 MySQL 预准备语句中获取一列


fetch one column from mysql prepared statement

我一直在使用预准备语句做一些工作,因为它们更安全,但是在以前版本的sql数组获取($query->fetch_array(MYSQL_ASSOC))中,它不允许从数组中返回一个项目。

function getForumInfo( $id, $col ){
    global $mysqli, $db_table_prefix;
    $stmt = $mysqli->prepare("SELECT ? FROM forums WHERE id = ?");
    $stmt->bind_param("si", $col, $id);
    $stmt->execute();
    $stmt->bind_result($val);
    $out = $stmt->fetch()[$val];
    $stmt->close();
    return $out;
}

有些东西看起来不对劲。

如果我要执行以下操作:

echo getForumInfo( 7, 'name');

它会只返回列名中的值,其中 id = 7?

准备语句中的标记不允许用于标识符(如表名或列名)、命名要由 SELECT 语句返回的列的选择列表中的标记,也不允许指定二元运算符的两个操作数(如=符号)。后一种限制是必要的,因为无法确定参数类型。也不允许将标记与NULL进行比较 ? IS NULL。你应该做这样的事情:

function getForumInfo( $id, $col ){
    global $mysqli, $db_table_prefix;
    $stmt = $mysqli->prepare("SELECT {$col} WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    // and so on...

现在,对于您的主要问题:

$out = $stmt->fetch()[$val];

不会产生您的结果。您已经拨打了bind_result电话;因此,只需使用以下方法:

$stmt->bind_result($out);
$stmt->fetch();
$stmt->close();
return $out;    // It could be `$val` if you use bind_result to $val