0

I have an array where the keys represent each column in my database. Now I want a function that makes a mysql update query. Something like

    $db['money'] = $money_input + $money_db;

    $db['location'] = $location

    $query = 'UPDATE tbl_user SET '; 

            for($x = 0; $x < count($db); $x++ ){

            $query .= $db something ".=." $db something

            }

    $query .= "WHERE username=".$username." ";      
0

4 Answers 4

3

You want foreach:

$values = array();
foreach($db as $column => $value){
    $values[] = $column . "='" . mysql_real_escape_string($value) . "'";
}
$query .= implode(',', $values);

But this will set all values as strings (not sure if MySQL makes automatic conversion), you might want to test with is_numeric first:

if(!is_numeric($value)) {
    $value = "'" . mysql_real_escape_string($value) . "'";
}
$values[] = $column . "=" . $value;

Update:

Whenever you set string values in a query, you have to put them into quotation marks. Hence you have to write:

$query .= "WHERE username='".$username."'";

(note the single quotation marks).

Using sprintf can make the whole thing much clearer.

Sign up to request clarification or add additional context in comments.

3 Comments

@DrColossos nope, it doesn't.
@Col. Shrapnel: I know I'm gonna regret this but just for the fun: Thank you for that productive comment. I'm looking forward to reading your answer to this question.
Lol :) I seldom write answers and this question is definitely not one requiring my contribution :)
0

something like this:

function mysql_update_array($table, $data, $id_field, $id_value) {
    foreach ($data as $field=>$value) {
        $fields[] = sprintf("`%s` = '%s'", $field, mysql_real_escape_string($value));
    }
    $field_list = join(',', $fields);

    $query = sprintf("UPDATE `%s` SET %s WHERE `%s` = %s", $table, $field_list, $id_field, intval($id_value));

    return $query;
}

Please note that the code is NOT mine!

2 Comments

@2astalavista so you just down-voted the solution because you think the code is ugly?! :-)
by the way, why are my comments disappeared? :O
0

You could use array_keys to extract the names of the array elements and then simply use something like...

$query .= $keys[$x] . '="' . mysql_real_escape_string($db[$keys[$x]]) .'" ';

...within the for loop.

(I've presumed the presence of a...

$keys = array_keys($db);

... after you've defined the $db values in the above.)

That said, I'm really not sure I'd recommend such a "one size fits all" approach.

Comments

0
foreach($array as $attr => $val)
    $items[] = "$attr='$val'";    
mysql_query("INSERT INTO table SET ".implode(',', $items));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.