note 41720 deleted from function.mysql-query by philip
| From: | philip@php.net | Date: | Wed, 06 Apr 2005 18:03:41 +0000 |
| Subject: | note 41720 deleted from function.mysql-query by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-87603@lists.php.net to get a copy of this message | ||
Note Submitter: d at koteroff dot ru
----
Here is better placeholder replacement function. Use
mysql_qw("SELECT * FROM t WHERE name=?", $name)
instead of
mysql_query("SELECT * FROM t WHERE name='$name'")
- it is much more secure. Why PHP developers have not included this (or similar) function in PHP
core? Mystery.
<?php
// result-set mysql_qw($connection_id, $query, $arg1, $arg2, ...)
// - or -
// result-set mysql_qw($query, $arg1, $arg2, ...)
function mysql_qw() {
$args = func_get_args();
$conn = null;
if (is_resource($args[0])) $conn = array_shift($args);
$query = call_user_func_array("mysql_make_qw", $args);
return $conn!==null? mysql_query($query, $conn) : mysql_query($query);
}
// string mysql_make_qw($query, $arg1, $arg2, ...)
function mysql_make_qw() {
$args = func_get_args();
$tmpl =& $args[0];
$tmpl = str_replace("%", "%%", $tmpl);
$tmpl = str_replace("?", "%s", $tmpl);
foreach ($args as $i=>$v) {
if (!$i) continue;
if (is_int($v)) continue;
$args[$i] = "'".mysql_escape_string($v)."'";
}
for ($i=$c=count($args)-1; $i<$c+20; $i++)
$args[$i+1] = "UNKNOWN_PLACEHOLDER_$i";
return call_user_func_array("sprintf", $args);
}
?>