0

我一直在使用准备好的语句做一些工作,因为它们更安全,但是在以前版本的 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?

4

1 回答 1

3

准备语句中的标记不允许用于标识符(例如表名或列名),不允许用于命名SELECT语句要返回的列的选择列表中,或者指定二元运算符的两个操作数,例如=符号。后一个限制是必要的,因为不可能确定参数类型。也不允许将marker与NULLby进行比较? 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
于 2013-10-17T23:17:05.417 回答