tags:

views:

127

answers:

5

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

A: 

$sql = trim($sql, ' AND ');

Jud Stephenson
`trim()` trims each of the characters A/N/D/space -- not the full string in a row.
Coronatus
True, good catch.
Jud Stephenson
+2  A: 
$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);
Coronatus
A: 

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.

David
+12  A: 

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);
Casey Hope
+1  A: 

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.

codaddict
@downvoter: Care to explain ?
codaddict