Positional parameters become a nightmare when dealing with more than 3 or 4 parameters. Named parameters are verbose. I'm thinking of doing this:
query("SELECT * FROM users WHERE username = ", $username, " AND password = ", $password开发者_如何学JAVA)
With dynamic parameters (using func_get_args()
), every second one being transformed into a positional parameter.
I've never seen this before and wanted to know if anyone has done this before and why/why not?
Named parameters don't have to be verbose, at least not compared to positional parameters. You could use shortened versions that are still obvious:
$st = $dbh->prepare('SELECT * FROM users WHERE username = :u AND password = :p');
$st->bindValue(':u', $username);
$st->bindValue(':p', $password);
$st->execute();
It's a clever idea. The only problem I see is how to distinguish between SQL and passed-in variables. Unless you make an assumption that every second arg is a variable. I just think that assumption is fragile, and obfuscates things more than makes them clear.
Better way would probably be to use interpolation:
query("SELECT foo FROM bar WHERE id = #{id}", array("id" => "23"));
Then write logic to interpolate these.
I don't think positional parameters are so bad... this is my favorite method:
function mysql_safe_string($value) {
if(is_numeric($value)) return $value;
elseif(empty($value)) return 'NULL';
elseif(is_string($value)) return "'".mysql_real_escape_string($value)."'";
elseif(is_array($value)) return implode(',',array_map('mysql_safe_string',$value));
}
function mysql_safe_query($format) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
$query = vsprintf($format,$args);
$result = mysql_query($query);
if($result === false) echo '<div class="mysql-error"><strong>Error: </strong>',mysql_error(),'<br/><strong>Query: </strong>',$query,'</div>';
return $result;
}
// example
$result = mysql_safe_query('SELECT * FROM users WHERE username=%s', $username);
精彩评论