问题
I have an array represents WHERE clause of my SQL query.
$qWhere= array("cName" => "Turgay Metal", "cTelephone" => "5556162");
my function is: (simplified)
<?php
function getAll($tableName,$qWhere="") {
$qWhere = $qWhere == "" ? $qWhere : (" WHERE " . $qWhere);
$sql = "SELECT * FROM $tableName $qWhere";}
So i need to write another function to kinda serialize array with foreach
as $k = '$v'
and then join " AND " then return the string. Finally supply the string into main function:
function arr2sql($qWhere) {
foreach ($qWhere as $key=>$value) { $fields[] = sprintf("%s = '%s'", $key, secure($value));}
$field_list = join(' AND ', $fields); unset($qWhere);
return $field_list;
}
Is this the correct way or may it be achieved more clean and profesionally?
Thanks for help.
回答1:
I think it looks pretty good; I like it. I assume secure()
protects from sql injection. I don't really see anything I would change.
You could take braces out of the for loop since its one statement, but that's no biggy
foreach ($qWhere as $key=>$value)
$fields[] = sprintf("%s = '%s'", $key, secure($value));
来源:https://stackoverflow.com/questions/8021866/pass-array-keys-and-values-to-mysql-query-string