Skip to content

Instantly share code, notes, and snippets.

@daGrevis
Created January 24, 2012 13:45
Show Gist options
  • Save daGrevis/1670232 to your computer and use it in GitHub Desktop.
Save daGrevis/1670232 to your computer and use it in GitHub Desktop.
Assoc array to SQL where
<?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