且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP在表名中从mysql_real_escape_string更改为PDO

更新时间:2023-02-26 10:02:55

您将无法转义表名(我希望$ tablename不是来自外部来源-如果是,则需要将允许使用的表名列入白名单).在PDO中,您的代码可能类似于:

You won't be able to escape the table name (I hope that $tablename isn't coming from an outside source - If it is, you will need to whitelist what table names are allowed). In PDO, your code could look something like:

$allowedTables = array('posts', 'users');
if(!in_array($tablename, $allowedTables)){
    throw new Exception('Invalid table name: ' . $tablename);
}

$keyword = 'something';
$stmt = $dbh->prepare("SELECT * FROM " . $tablename . " WHERE keyword = :keyword");
$stmt->bindParam(':keyword', $keyword);
$stmt->execute();