【问题标题】:Mysqli prepared statement column with variable [duplicate]带有变量的Mysqli准备好的语句列[重复]
【发布时间】:2017-01-11 18:26:18
【问题描述】:

我的代码必须使用自定义变量作为列来更新查询。

如何安全地绑定列名?

$username = 'MyUsername'; 
$rank = 'Administrator';
$server = 'Node5';

$stmt = $connection->prepare("UPDATE staff_members SET ?=? WHERE Username=? LIMIT 1");
$stmt->bind_param("sss", $server, $rank, $username);
$stmt->execute();

【问题讨论】:

    标签: php mysqli


    【解决方案1】:

    不可能为列名或表名使用参数。相反,它们必须在使用前明确过滤掉,使用white list 方法。

    // define a "white list"
    $allowed = ['Node5', 'Node4'];
    
    // Check the input variable against it 
    if (!in_array($server, $allowed)) {
        throw new Exception("Invalid column name");
    }
    
    // now $server could be used in the SQL string
    $sqlString = "UPDATE staff_members SET $server=? WHERE Username=?";
    $stmt = $connection->prepare($sqlString);
    $stmt->bind_param("ss", $rank, $username);
    $stmt->execute();
    

    【讨论】:

      猜你喜欢
      • 2012-12-01
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 2011-02-02
      • 2014-11-14
      相关资源
      最近更新 更多