问题
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