Updating field on multiple rows

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

It's me with my PHP problems again! This time I am trying to update a number of fields in my database at once.

First i have this page (took the password protection off so you can see it):

http://www.housing.uwaterloo.ca/profiles/admin/listprofiles.php

I need to check a number of boxes in the approved column, then update those records in the database. I got this working with this code:

<?php
// grab fields that were submitted
$fields = $_POST[\"approve\"]; //takes the data from a post operation and puts them into an array
    if (
$fields == \"\") {die(\"no records submitted\");} // if the fields array is empty, say that nothing was submitted

include '../library/db_connect.php'; // include database info

foreach (
$fields as $ID) { // looping through the fields array
    echo
$ID . \"<br />\"; // just print them to make sure it's working okay
    mysql_query(\"UPDATE profiles_individual SET approved = '1' WHERE ID =
$ID\") or die('Database query error');       
}
?>

Then Liam told me it's not good to write to the database every time the loop goes through. It's better to use the loop to build up the query string then write it at once at the end. I think I can do that by adding the $ID onto a string, but I'm not sure what the query should look like in this case. I figure it should be something like this:

"UPDATE profiles_individual SET approved = '1' WHERE ID = id1, id2, id3, id4"

But that's not right. There are lots of search results for this on google but I can't seem to find the right solution.

I could just ignore this because I probably won't be releasing more than a few records at a time.

timjpriebe's picture

He has: 2,667 posts

Joined: Dec 2004

Something more like this:

UPDATE profiles_individual
SET approved = '1'
WHERE ID IN ('id1', 'id2', 'id3', 'id4')

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

Okay, great. Now I have it building the string until it looks like this:

UPDATE profiles_individual SET approved = '1' WHERE ID IN ('id1','id2','id3',)

It's giving an error because of that trailing comma, right? I'll see if I can figure out how to get rid of that...

Update: done! That was easy Smiling Thanks for the help!

timjpriebe's picture

He has: 2,667 posts

Joined: Dec 2004

No problem!

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.