所以我试图创建一个基于多维数组生成SQL查询字符串的函数.
例:
function createQueryString($arrayToSelect,$table,$conditionalArray) { $queryStr = "SELECT ".implode(",",$arrayToSelect)." FROM ".$table." WHERE "; $queryStr = $queryStr.implode(" AND ",$conditionalArray); /*NEED HELP HERE*/ return $queryStr; } $columnsToSelect = array('ID','username'); $table = 'table'; $conditions = array('lastname'=>'doe','zipcode'=>'12345'); echo createQueryString($columnsToSelect,$conditions); /*will result in incorrect sql Syntax*/
正如你所看到的那样,我需要第三行的帮助,因为它正在打印
SELECT ID,username FROM table WHERE
lastname AND zipcode
但它应该是打印
SELECT ID,username FROM table WHERE
lastname = ‘doe’ AND zipcode = ‘12345’
实际上并没有打破一个多维数组. $条件是一个关联数组.
只需在函数createQueryString()中使用foreach循环.这样的事情应该工作,请注意它是未经测试的:
$terms = count($conditionalArray); foreach ($conditionalArray as $field => $value) { $terms--; $queryStr .= $field . ' = ' . $value; if ($terms) { $queryStr .= ' AND '; } }