使用 IN() 函数准备 MySQL 语句 [英] Prepare MySQL statement with IN() function
本文介绍了使用 IN() 函数准备 MySQL 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在我这样做了:
$params = array(1,2,3);
$sql = 'select * from foo where bar in (%s)';
$sql = sprintf($sql,
implode(',', $params)
);
$params
由用户提供,因此显然不安全.我怎样才能解决这个问题?我更喜欢使用 Zend 这样的框架.
$params
is supplied by a user so it's obviously unsafe.
How can I fix this? I would prefer using a framework like Zend.
推荐答案
You could use prepared statements with PDO:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$params = array(1,2,3);
$values = implode(',', array_fill(0, count($params), '?')); // ?,?,?
$sql = "select * from foo where bar in ($values)";
$stmt = $dbh->prepare( $sql );
$stmt->execute( $params );
通过使用准备好的语句,您可以避免对数据进行转义.不过,您仍然需要对其进行验证.
By using prepared statements, you avoid the need to escape your data. You will still need to validate it though.
这篇关于使用 IN() 函数准备 MySQL 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文