Thursday, April 12, 2012

How to update a table column based on it's relation to another table?

I have a table called "profiles". There was a column in this table called "user_id" which I have changed the name to "username" and the type from INT(11) to Varchar(255) . However the contents of this column are still numeric ids.



These ids correspond to another table called "users". That table has fields called "user_id" and "username". For each row on the "profiles" table I need to first check to see what the username field has for the id and do a look up on the users table to get the username that correcponds to that id and then update the profile table's username value for with the proper username.



Profiles table:



username | blah blah...
------------------------
1 | ...


Users table:



user_id | username
------------------------
1 | Joe


I need the value for the username field on the profiles table to be updated to "Joe".



I came up with this php script but it stops working after updating just 4 records for some reason:



    $sql = 'SELECT username FROM profiles';
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
$id = $row['username'];
$sql = 'SELECT username FROM users WHERE user_id = '. $id;
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
$sql = "UPDATE profiles SET username = '".$row['username']."' WHERE username = $id";
$query = mysql_query($sql);
if(!$query) {
echo 'error!';
}
}
}


My script isn't all that efficient to begin with, although that's not that big an issue since the table has just 50k records. Anyway what would be a way to do this directly from mysql?





1 comment:

  1. You are manipulating the $row variable inside the first loop. Obviously it does not work. Try giving the variable in inner loop a different name.

    And not only that almost all the variables you are using, outside the first loop, you are using the same names inside the inner loop.

    Also coming to db schema I would prefer ids to be foreign keys not usernames because querying using ids would be faster than with columns of type varchar.

    One more suggestion is that there is no need to use

    while($row = mysql_fetch_assoc($query))
    because there would be only one row

    ReplyDelete