note 64194 deleted from function.mysql-real-escape-string by aidan
| From: | aidan@php.net | Date: | Sun, 24 May 2009 19:46:58 +0000 |
| Subject: | note 64194 deleted from function.mysql-real-escape-string by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155940@lists.php.net to get a copy of this message | ||
Note Submitter: eric256 at gmail dot com
----
Hey,
Since SQL injection is such a fear it is beyond me as to why this hasn't been included yet. I
set this function up to take a query with ?'s in it and replace those with the correctly quoted
values. I don't do the "smart quoteing" i quote it in the SQL because i like to see
the quotes there.
<?php
function db_query($query) {
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
return $result;
}
?>
call it like
<?php
$results = db_query("SELECT * FROM users WHERE username='?' AND password =
PASSWORD('?');", $username,$password);
?>
This automagicaly quotes them and executes the query for you and also dies if there is an error in
the query.