Tuesday, 15 March 2011

php - mysql Update in foreach loop -



php - mysql Update in foreach loop -

i trying figure out how update mysql table array.

the table has 3 fields: id, rate, pol_id. "insert into" works perfect:

foreach ($rates $rn=>$rv) { $sql3=mysql_query("insert `rates` (`rate`, `pol_id`) values ( '$rv', '$polid',)") or die ("unable issue query sql2: ".mysql_error()); }

$rates array dynamic input fields.

so example:

id | rate | pol_id ========================= 1 | 5.6 | 272 2 | 6.3 | 272 3 | 7.9 | 272

now edit values in input fields need update table:

i have tried this:

foreach ($rates $rn=>$rv) { $sql3=mysql_query("update `rates` set `rate`='$rv' `pol_id`='$polid'")or die ("unable issue query sql3: ".mysql_error()); }

but isn't working, updates rows lastly value.

can ypu please help me this?

your $polid variable not beingness changed within foreach loop. causes statement true elements in rates table have same pol_id (specified in $polid). sets value 'all' entries (with pol_id = $polid) lastly value entered (in $rv).

you seek adding sec status statement if know old value of rate this:

$sql3=mysql_query("update `rates` set `rate`='$rv' `pol_id`='$polid' , `rate`={old_value}")or die ("unable issue query sql3: ".mysql_error()); }

a nicer method utilize id column of rates (as guaranteed unique) first performing query retrieve id of entry want , subsequently utilize id in update query.

$query1 = mysql_query("select id rates {your desired condition}; /* assign result of $query1 $id */ $sql3=mysql_query("update `rates` set `rate`='$rv' `pol_id`='$polid' , `id` = $id)or die ("unable issue query sql3: ".mysql_error()); }

you can allow pol_id = '$polid' out of query because of id beingness unique.

php mysql

No comments:

Post a Comment