0

I have the following loop to add several users to a database, however it only works when only one user is added into a form.

echo "The following names have been added to $cname<br><br>";
$query = "";
for ($i = 0; $i < count($fname); $i++) {
  $query = $query . "INSERT INTO Students (firstName, lastName, year, class, school, email) " 
  ." VALUES ('{$fname[$i]}','{$lname[$i]}','{$year}','{$cname}','{$sch}','{$uname[$i]}'); ";
  echo $fname[$i] . " " . $lname[$i] . " " . $uname[$i];
  }

if ($mysqli->query($query)) {
    $id = $mysqli->insert_id;
    error_log("Inserted {$firstname} as ID {$id}");
    return true;
} else {
    error_log("Problem inserting {$query}");
    return false;
}

Do I just need to add ($mysqli->query($query) to each iteration? Or just move the 'if' clause inside the loop? Or is there a better way.

Thank you.

3
  • what is your echo result? and how to you pump value to this php file? Commented Apr 2, 2014 at 6:35
  • echo is blank and no data is added to DB. 'if' returns false and page redirects to form. If only one name entered in form, it works without problem. Commented Apr 2, 2014 at 6:37
  • can you show your form aas well? Commented Apr 2, 2014 at 6:38

2 Answers 2

1

At the moment your query is trying to send muliple sql queries at once and it fails. You should change the way you build query:

$query = "INSERT INTO Students (firstName, lastName, year, class, school, email) VALUES ";
for ($i = 0; $i < count($fname); $i++) {
  $query .= $i>0 ? ',':'';
  $query .="('{$fname[$i]}','{$lname[$i]}','{$year}','{$cname}','{$sch}','{$uname[$i]}') ";
  echo $fname[$i] . " " . $lname[$i] . " " . $uname[$i];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Better leave out the semicolon after each VALUES tuple.
It doesn't really matter, as you will have to "if" it anyway - otherwise it will leave semicolon after last data set and fail.
0

Better put if clause in the loop. Have you tried it?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.