PHP爆关联数组 [英] PHP Implode Associative Array
问题描述
所以我试图创建生成基于多维阵列上的SQL查询字符串的函数。
例如:
函数createQueryString($ arrayToSelect,$表,$ conditionalArray){
$ queryStr =SELECT.implode(,$ arrayToSelect),从$表WHERE。;
$ queryStr = $ queryStr.implode(AND,$ conditionalArray); / *需要帮助HERE * /
返回$ queryStr;
}$ columnsToSelect =阵列('ID','用户名');
$表='表';
$条件=阵列('姓'=>母鹿,拉链code'=>'12345');
回声createQueryString($ columnsToSelect,$表,$条件); / *会导致不正确的SQL语法* /
你可以看到我需要3行帮助,因为它是目前印刷
选择ID,用户名FROM表WHERE
姓氏和Zip code
块引用>但是应当打印
选择ID,用户名FROM表WHERE
姓氏='美国能源部和zip code =12345
块引用>解决方案您实际上并不爆多维数组。 $条件是关联数组。
只需使用foreach循环的功能createQueryString()内。像这样的东西应该工作,注意这是未经测试的:
$学期=计数($ conditionalArray);
的foreach($ conditionalArray为$字段=> $值)
{
$ terms--;
$ queryStr。= $领域。 =。 $价值;
如果($计算)
{
$ queryStr ='和'。
}
}注意:要prevent SQL注入,其值应逃脱和/或引用适当/必要采用DB。不只是复制和粘贴;想!
So I'm trying to create a function that generates a SQL query string based on a multi dimensional array.
Example:
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, $table, $conditions); /*will result in incorrect SQL syntax*/
as you can see I need help with the 3rd line as it's currently printing
SELECT ID, username FROM table WHERE lastname AND zipcode
but it should be printing
SELECT ID, username FROM table WHERE lastname = 'doe' AND zipcode = '12345'
解决方案You're not actually imploding a multidimensional array. $conditions is an associative array.
Just use a foreach loop inside your function createQueryString(). Something like this should work, note it's untested.:
$terms = count($conditionalArray); foreach ($conditionalArray as $field => $value) { $terms--; $queryStr .= $field . ' = ' . $value; if ($terms) { $queryStr .= ' AND '; } }
Note: To prevent SQL injection, the values should be escaped and/or quoted as appropriate/necessary for the DB employed. Don't just copy and paste; think!
这篇关于PHP爆关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!