Page 1 of 1

[SOLVED] Inserting Array into Database

Posted: Fri Mar 24, 2006 10:19 am
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.

Posted: Fri Mar 24, 2006 10:30 am
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()); 
}

Posted: Fri Mar 24, 2006 10:43 am
by Cateyes
Thanks again Feyd I feel like I have a direct line to you for how fast you respond you ever sleep? lol