views:

230

answers:

3

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.

+2  A: 

what about PDO ?

http://php.net/manual/en/book.pdo.php

Haim Evgi
+2  A: 

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.

ax
+1  A: 

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/

jckdnk111
nice idea. however, this a) still doesn't let us access server-side Prepared Statements, and b) has bugs (e.g. int parameters (`1`) get quoted (`'1'`), which might lead to problems with strict sql). i guess it's not so trivial to write a bug free `prepare()`.
ax