Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Implode Associative Array

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'

like image 774
st4ck0v3rfl0w Avatar asked Jul 18 '10 18:07

st4ck0v3rfl0w


1 Answers

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!

like image 136
George Marian Avatar answered Sep 21 '22 12:09

George Marian