Pass array keys and values to Mysql Query String

不打扰是莪最后的温柔 提交于 2020-01-15 23:03:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!