Created
January 24, 2012 13:45
-
-
Save daGrevis/1670232 to your computer and use it in GitHub Desktop.
Assoc array to SQL where
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Makes SQL compatible WHERE statement from assoc array where array's keys are table's columns, but values - rows. | |
* | |
* @param array `array('a' => 'foo', 'b' => 123, 'c' => 'bar',)` | |
* @return string `WHERE `a` = 'foo' AND `b` = 123 AND `c` = 'bar'` | |
* | |
* @author daGrevis | |
*/ | |
function sql_where(array $where) { | |
$sql = ''; | |
$i = 0; | |
foreach ($where as $k => $v) { | |
if ($i === 0) { | |
$sql .= 'WHERE'; | |
} else { | |
$sql .= ' AND'; | |
} | |
if (is_string($v)) { | |
$v = "'$v'"; | |
} | |
$sql .= " `$k` = $v"; | |
++$i; | |
} | |
return $sql; | |
} | |
$foo = array('a' => 'foo', 'b' => 123, 'c' => 'bar',); | |
echo sql_where($foo); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment