Re: Inserting Records from a table into another table..

From: Date: Thu, 22 May 2003 13:52:33 +0000
Subject: Re: Inserting Records from a table into another table..
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-148563@lists.php.net to get a copy of this message
> How can I take records from one table into another based on a criteria.. > > Let's say I have a table xyz with a field "username" & "user_id" > Another table abc with a field "name" and "id" > > Table XYZ has many rows with "user_id" having records .. but "username" > being empty. > The name & id field in table abc are corresponding to each other .. > i.e., if user = "Rahul" and id = "26" .. then it will be the same for > xyz. > > What I want to do is, pick up "name" from table abc and insert it into > "username" in table xyz .. based on its' ID.. You're not inserting, your updating. You insert a new row, you update an existing row. So, something like this should work (assuming mysql) $rs = mysql_query("SELECT id, name FROM abc a, xyz x WHERE a.id = x.user_id AND x.username = ''); while($r = mysql_fetch_assoc($rs)) { $rs2 = mysql_query("UPDATE xyz SET username = '{$r['name']}' WHERE user_id = {$r['id']}"); } Adapt to your needs, add in some error checking, etc. If your database supports JOINs on UPDATE queries, you could probably do this all with one query. ---John Holmes...

« previous php.general (#148563) next »