Question

I have a string and the final output is:

UPDATE in-the-press SET title='Test 2',date='2014-05-06',description='Blah, Blah, Blah',image='admin-uploads/test.jpg',WHERE id = 1

This was generated via here:

$sql = "UPDATE " . $array['tableName'] . " SET ";

                foreach($array as $row => $value){
                        if($row == 'id' || $row == 'tableName' || $row == 'submit'){
                                continue;
                        }
                        $sql .= $row . "='" . $value . "',";
                }
                $sql .= "WHERE id = " . $array['id'];

How would I go about removing the last comma before the WHERE or would I want to use a counter to say on last item in for each do not have the comma.

Was it helpful?

Solution 2

I always do it this way. Just create array for conditions and then implode it as below:

$sql = "UPDATE " . $array['tableName'] . " SET ";
            $set = array();
            foreach($array as $row => $value){

                    if($row == 'id' || $row == 'tableName' || $row == 'submit'){
                            continue;
                    }
                    $set[] = $row . "='" . $value."'";
            }
            $sql .= implode(',' $set);
            $sql .= "WHERE id = " . $array['id'];

Of course you should consider using prepared statements using for example PDO for queries or at least you should use functions like mysql_real_escape_string / mysqli_real_escape_strin

OTHER TIPS

$terms = array()
foreach($array as $row => $value){
    $terms[] = "$row = '$value'";
}
$term_str = implode(',', $terms);

Hopefully you've accounted for SQL injection attacks somewhere else and the values in $array are "safe"...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top