update mysql db with php loop from array

2019-08-23 05:14发布

问题:

I want update a column in mysql with a loop. I have two arrays that are pulled from another database every 4 hours. The first has a station number that is in my db as an index. The second is the data I want to update.

    $stano = 13235000,13236500,13237920
    $nt = 379,49,131

Currently I simply update with a bunch of queries:

 mysql_query("UPDATE gages SET cfs = '".$nt[3][2]."' WHERE sgs = '".$stano[3][1]."'")
 mysql_query("UPDATE gages SET cfs = '".$nt[4][2]."' WHERE sgs = '".$stano[4][1]."'")
 mysql_query("UPDATE gages SET cfs = '".$nt[5][2]."' WHERE sgs = '".$stano[5][1]."'")

It seems it would make more sense to run some kind of loop and update all in one shot. But I'm not sure how to step up the number of the array index with each loop. Unfortunately, I seem to have reached my ceiling of understanding with php. Certainly my patience, as I have spent a day trying to figure this out.

回答1:

I don't understand the way you describe your data, but if i base myself on the calls you make already, i can suppose that this will work:

for($i = 0; $i < count($nt); $i++) {
  mysql_query("UPDATE gages SET cfs = '".$nt[$i][2]."' WHERE sgs = '".$stano[$i][1]."'");
}