Looping through an array result and inserting again

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
valency
Forum Newbie
Posts: 1
Joined: Mon Jun 30, 2008 7:48 pm

Looping through an array result and inserting again

Post by valency »

I will like to loop trrough an array of database results and then insert each of those result again into the same database so that it gets viewed as a copy on the html page when such a button of copy is clicked....
here is my code already:





$sql = "SELECT * FROM DataScreenQuest WHERE screenID=".$_REQUEST["SCRID"];
$RES = mysql_query($sql) or die('Query failed: ' . mysql_error().'<br>'.$sql);

$DATA = mysql_fetch_assoc($RES);



//i tried this and its only returning just one result instead of 4results in the database...and its also jumping the first result and inserting into the database again only the 2nd result of the select statement...how do i loop thru the result such that, as its selecting thru the database results, its inserting into the database all the results from the select so that we have an exact copy of the whole select query results returned into the database again but with a different ID which of course gets inserted as an autoincrement....pls help with the logic...



while($DATA = mysql_fetch_assoc($RES))
{

$screenID = mysql_insert_id();
$QuestionText = $DATA[QuestionText] ;
$DisplayOrder = $DATA[DisplayOrder] ;
$Active = $DATA[Active] ;
$AllRequired = $DATA[AllRequired] ;

echo $DATA;


$sql = "INSERT INTO DataScreenQuest(ID, screenID, QuestionText, DisplayOrder, Active, AllRequired)VALUES('','$screenerID','$QuestionText','$DisplayOrder','$Active','$AllRequired')";
//insert this query nto thedatascreene questions as new so we can have it displayed but with a new screener ID now
$result=mysql_query($sql);

}

will this loop thru all result and then insert for each again into the same database? please help..
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Re: Looping through an array result and inserting again

Post by SidewinderX »

Code: Select all

while($DATA = mysql_fetch_assoc($RES))
{
 
 
}
This will loop through all the rows in your database.

Code: Select all

$QuestionText = $DATA[QuestionText];
$DisplayOrder = $DATA[DisplayOrder];
$Active = $DATA[Active];
$AllRequired = $DATA[AllRequired];
Since QuestionText, DisplayOrder, Active, and AllRequired are not constants, you need to surround them with single quotes: $DATA['QuestionText']

Your query appears to be fine.
Post Reply