简体   繁体   中英

update mysql table with php array

I've a PHP multidimensional array like this:

username_1, user_state, user_score, user_views, ...
username_2, user_state, user_score, user_views, ...
username_3, user_state, user_score, user_views, ...
username_4, user_state, user_score, user_views, ...
...................................................

I could write a loop in PHP, but with several hundred users, I don't want it to hit mysql db for each user. Instead, I want to somehow pass the array to MySQL and have it take care of all the updates.

Now, in SQL Server, I could write a stored procedure to take care of all this, but what would be the most efficient/simplest way to take care of this in MySQL?

(I did google it up, but most of them loop in PHP instead of MySQL.)

i think its better to avoid stored procedure. I'll tell you one solution. Mysql supports inserting multiple records in a single query. So you do one thing write a for loop in your php program and create one big query to insert into database and after that for loop run that query.

    $sql="update tablename set username_1='demo', user_state='active', user_score='100', user_views='20' where id='1'";
     mysql_query($sql);
  1. You can use REPLACE instead of UPDATE which has the same syntax as INSERT (so you can process multiple records in a single query) : http://dev.mysql.com/doc/refman/5.5/en/replace.html

  2. You may also use prepared statements : http://php.net/manual/en/pdo.prepare.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM