简体   繁体   中英

Insert into a db data coming from a loop (while)

hi have a code like this

for ($i=0; $i<=count($query)+1 ; $i++)
 {
$sql ="SELECT * FROM $tabella[$i] WHERE id='1'";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);

while($row = mysql_fetch_array($result))
{
$name=$row['name'];
$surname=$row['surname'];

INSERT INTO student (name,surname) Values ($name,$surname)
} 

}

It insert the data only from the first table he found so only one name and one surname and not all the $name and $surname with id=1

How can I resolve it

Here is the edit to your script and possible problems I fouund:

for ($i=0; $i<=count($query)+1 ; $i++)           //Why is there a +1?
 {
$sql ="SELECT * FROM $tabella[$i] WHERE id='1'"; //Your issue could be here, tabella[$1]
$result=mysql_query($sql);                       //may not be totally there
$numrows=mysql_num_rows($result);                //Try to echo your SELECT $sql query 
                                                 //to check

                                                 //Why do you have $numrows? I dont see
                                                 //that being used anywhere

while($row = mysql_fetch_array($result))
{
$name=$row['name'];
$surname=$row['surname'];

INSERT INTO student (name,surname) Values ($name,$surname) //Your INSERT statement 
                                                           //looks ok
                                                           //Try to use single/or double
                                                           //quotes around the values
                                                           //I like having `name`,  
                                                           //`surname` around fields
} 

}

Check with comments. It's recommended you use Prepared/or PDO but in most cases websites that use straight mysql functions are older or have already been coded so there aren't any changes of being redone; its a lot of work. This makes sense when you're starting fresh. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM