PHP在表名中从mysql_real_escape_string更改为PDO [英] PHP changing from mysql_real_escape_string to PDO in table name

查看:29
本文介绍了PHP在表名中从mysql_real_escape_string更改为PDO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用mysql_real_escape_string来转义mysql查询中的变量.我知道如何使用bindValue,但是当我尝试从变量中插入表名时,我有一个关于保护的问题.例如

I currently use mysql_real_escape_string to escape variable in mysql query. I know how to use bindValue, but I have a question about protection when I'm trying to insert table name from variable. For example

$tablename = mysql_real_escape_string($name_from_form);
$get = mysql_query("SELECT * FROM ".$tablename." WHERE keyword='something'");

有人可以帮我举一个如何做PDO准备好的语句的例子吗?

Can anybody help me with an example of how to do PDO prepared statements which will do the same as above?

推荐答案

您将无法转义表名(我希望$ 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();

这篇关于PHP在表名中从mysql_real_escape_string更改为PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆