Prepare MySQL statement with IN() function

空扰寡人 提交于 2020-01-16 00:51:12

问题


Now I do:

$params = array(1,2,3);
$sql = 'select * from foo where bar in (%s)';

$sql = sprintf($sql, 
    implode(',', $params)
);

$params is supplied by a user so it's obviously unsafe. How can I fix this? I would prefer using a framework like Zend.


回答1:


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.




回答2:


You have to make each array entry safe. Either using mysql_real_escape_string(), or in your case, just by casting to int. The most generic method would be the following:

function quoteString( $string ) {
  return "'" . mysql_real_escape_string($string) . "'";
}

$quotedParams = array_map("quoteString", $params);

$sql = sprintf($sql, 
  implode(',', $quotedParams)
);

In your case, you could cast to int, so you could do it like this:

$intParams = array_map("intval", $params);

$sql = sprintf($sql, 
  implode(',', $intParams)
);


来源:https://stackoverflow.com/questions/7158078/prepare-mysql-statement-with-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!