Petre Gabriel
Petre Gabriel

Reputation: 141

How to update a table colum with data from an array?

I have a table without an AI index. I had to trim data from a colum, and now I need to update with result from trim, but with the cod I have now, only updates with the same value, last value from that array.

$i=0;
while ($row = $column->fetch_assoc()) {
$arr[$i] = trim($row['profile_value'],"\"");
$db->query("UPDATE `vwfl5_user_profiles` SET profile_value='".$arr[$i]."'");
$i++;
}

Thanks!

Upvotes: 0

Views: 38

Answers (3)

Don't Panic
Don't Panic

Reputation: 41810

You don't really need a loop for this. Just do it with one query.

$db->query("UPDATE `vwfl5_user_profiles` SET profile_value= TRIM( '\"' FROM profile_value)");

If you don't want to update every record, just add a WHERE clause with whatever criteria you used to get the results you are looping over.

$db->query("UPDATE `vwfl5_user_profiles` 
    SET profile_value = TRIM( '\"' FROM profile_value) WHERE... ");

Upvotes: 2

Ncx
Ncx

Reputation: 1792

You should add WHERE clause with table primary key to identify each item in the db:

$i=0;
while ($row = $column->fetch_assoc()) {
$arr[$i] = trim($row['profile_value'],"\"");
$db->query("UPDATE `vwfl5_user_profiles` SET profile_value='".$arr[$i]."' WHERE id = " . $row['id'] . "");
$i++;
}

Upvotes: 0

urban
urban

Reputation: 5682

2 things:

  1. Shouldn't you update a specific row? Ie: "UPDATE `vwfl5_user_profiles` SET profile_value='".$arr[$i]."' WHERE id=$row[id]" (given there is an id and is integer)
  2. I think you can do that with Trim Function

Upvotes: 0

Related Questions