I'm building a basic function, which builds out Mysql WHERE clauses based on how many are in the array.
$array = array('id' => '3', 'name' => 'roger');
$sql = "SELECT * FROM table WHERE ";
forea开发者_如何学JAVAch ($array as $k => $v) {
$sql .= $k . ' = ' . $v . ' AND ';
}
which will output
SELECT * FROM table WHERE id = 3 AND name = roger AND
However obviously I don't want that last AND, how do I go about removing it from the string?
Thanks
You could do
$sql = substr($sql, 0, -5);
But perhaps the more elegant solution is
$array = array('id' => '3', 'name' => 'roger');
$clauses = array();
foreach ($array as $k => $v)
$clauses[] = $k . ' = ' . $v;
$sql = "SELECT * FROM table WHERE " . implode(' AND ', $clauses);
$array = array('id' => '3', 'name' => 'roger');
$sql = "SELECT * FROM table WHERE ";
foreach ($array as $k => $v) {
$sql .= $k . ' = ' . $v . ' AND ';
}
$sql = substr(trim($sql), 0, -3);
I would do it this way:
$sql = "SELECT * FROM table WHERE 1=1 ";
// add "AND x=y" for every pair of key, value pair in the array.
foreach ($array as $k => $v)
$sql .= ' AND ' . $k . ' = ' . $v;
I've added a 1=1
to the where
clause so that your query will be valid even if the array $array
is empty.
$sql = trim($sql, ' AND ');
Reformulate the question. You're trying to put an AND after every clause except the last. It would be easier to put an AND before every clause except the first.
$first = true;
foreach ($array as $k => v) {
if (!$first) $sql .= ' AND ';
$first = false;
sql .= $k . ' = ' . $v;
}
Maybe not the easiest way in this case (other people mentioned using substr). However, I've found it a good tool to remember in general for situations like this.
精彩评论