开发者

MySQL UPDATE fieldnames from array with fieldvalues from array

I am trying to write a MySQL query (in PHP) that will update a set of fieldnames contained within an (imploded) array with a set of values contained within another (imploded) array.

What I have right now is this:

$edit= mysql_query ("UPDATE tablename SET `".$EXPfields."` = '".$EXPvalues."' 
WHERE ID = '$ID'");

But for $EXPfields = EXP1, ?EXP2?, ?EXP3

and $EXPvalues = Communications', 'Electronics', 'Engineering

(both imploded arrays, ? is actually a backtick: `)

I get the 开发者_StackOverflowfollowing error message:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' ?EXP2?, ?EXP3? = 'Communications', 'Electronics', 'Engineering' ' at line 2

(again, ? is actually a backtick `)

I've been playing around with this for ages, but I can't see where I have gone wrong, help pls! Thanks!


Update queries have the following syntax:

UPDATE table
SET column = expression
WHERE predicates;


You could loop through the array of fields and create a new array containing both column names and values. For example:

$update_sql = '';

for($i = 0;  $i < count($EXPfields);  ++i)
{
    $update_sql = "`" . $EXPfields[$i] . "` = '" . $EXPvalues[$i] . "', ";
}

$update_sql = substr($update_sql, 0, -2);

$edit = mysql_query("
    UPDATE
        tablename
    SET
        " . $update_sql . "
    WHERE
        ID = '$ID'");


UPDATE table
  SET
    field1 = expression1,
    field2 = expression2,
    field3 = expression3
 WHERE ...


You need to do comma separated field=value pairs. eg:

$query = UPDATE ?tablename? SET ?field1?='value1', ?field2?='value2' WHERE (?field3?='value3')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜