Hi, I'd like to know if it is possible to create a prepared statement with PHP and MySQL using the mysql library rather than the mysqli library.
I can't find anything on the PHP documentation.
Thanks.
Hi, I'd like to know if it is possible to create a prepared statement with PHP and MySQL using the mysql library rather than the mysqli library.
I can't find anything on the PHP documentation.
Thanks.
The PHP documentation quite clearly states (at the end of that page) that the mysql
extension does not support prepared statements. An alternative to mysqli
that supports prepared statements would be PDO_MYSQL
.
Why do you want to use a Prepared Statement?
If SQL injection is your concern you could always roll your own:
$fname = "Robert'); DROP TABLE students;--";
$lname = "Smith";
$pureSql = "SELECT FROM `users` WHERE `fname` = '$fname' AND `lname` = '$lname'";
$prepSql = "SELECT FROM `users` WHERE `fname` = :userfname AND `lname` = :userlname";
echo $pureSql, "\n";
echo prepare($prepSql, array('userfname' => $fname, 'userlname' => $lname)), "\n";
function prepare($sql, $params=array()){
if(strlen($sql) < 2 || count($params) < 1){
return $sql;
}
preg_match_all('/\:[a-zA-Z0-9]+/', $sql, $matches);
$safeSql = $sql;
foreach($matches[0] as $arg){
if(array_key_exists(ltrim($arg, ':'), $params)){
$safeSql = str_replace($arg, "'" . mysql_real_escape_string($params[ltrim($arg, ':')]) . "'", $safeSql);
}
}
return $safeSql;
} //prepare()
Output is:
SELECT FROM users
WHERE fname
= 'Robert'); DROP TABLE students;--' AND lname
= 'Smith'
SELECT FROM users
WHERE fname
= 'Robert\'); DROP TABLE students;--' AND lname
= 'Smith'
EDIT: forgot the xkcd link http://xkcd.com/327/