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 ";
foreach ($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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With