[SOLVED] Inserting Array into Database

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
Cateyes
Forum Commoner
Posts: 63
Joined: Mon Jun 14, 2004 5:06 pm

[SOLVED] Inserting Array into Database

Post by Cateyes »

Hey guys I was wondering if anyone could tell me why only the final person from the array is entered into the database I have 5 fields one that is id and auto_increment the other 4 would be first, last, user names as well as pw
here is the code probably something simple I hope see what you think

Code: Select all

//DATA BASE CONNECT
mysql_select_db($database_unknown, $unknown);
$query_rs_add_students = "SELECT * FROM student_accounts";
$rs_add_students = mysql_query($query_rs_add_students, $unknown) or die(mysql_error());
$row_rs_add_students = mysql_fetch_assoc($rs_add_students);
$totalRows_rs_add_students = mysql_num_rows($rs_add_students);

for($i=1;$i<17;$i++)
	{
	if ($first_name[$i] != "")
		{
$insertSQL = "INSERT INTO student_accounts (first_name, last_name, user_name, password) VALUES ('$first_name[$i]','$last_name[$i]','$final_username[$i]','$sin_4[$i]')";
		}
	}
  mysql_select_db($database_unknown, $unknown);
  $Result1 = mysql_query($insertSQL, $unknown) or die(mysql_error());
Thanks fo rthe help in advance guys.
Last edited by Cateyes on Fri Mar 24, 2006 10:43 am, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

each time $insertSQL is hit, the previous data in it is throw away. Something like this may be of more help

Code: Select all

$insertSQL = array();
for($i=1;$i<17;$i++)
    {
    if ($first_name[$i] != "")
        {
$insertSQL[] = "INSERT INTO student_accounts (first_name, last_name, user_name, password) VALUES ('$first_name[$i]','$last_name[$i]','$final_username[$i]','$sin_4[$i]')";
        }
    }
if(!empty($insertSQL))
{
  mysql_select_db($database_unknown, $unknown);
  foreach($insertSQL as $insert)
  {
    mysql_query($insert, $unknown) or die(mysql_error()); 
  }
}
Even faster running, but more database specific:

Code: Select all

$insert = 'INSERT INTO student_accounts (first_name, last_name, user_name, password) ';
$insertSQL = array();
for($i=1;$i<17;$i++)
    {
    if ($first_name[$i] != "")
        {
$insertSQL[] = "VALUES ('$first_name[$i]','$last_name[$i]','$final_username[$i]','$sin_4[$i]')";
        }
    }
if(!empty($insertSQL))
{
  mysql_select_db($database_unknown, $unknown);
  $insert .= implode(', ', $insertSQL);
  mysql_query($insert, $unknown) or die(mysql_error()); 
}
Cateyes
Forum Commoner
Posts: 63
Joined: Mon Jun 14, 2004 5:06 pm

Post by Cateyes »

Thanks again Feyd I feel like I have a direct line to you for how fast you respond you ever sleep? lol
Post Reply