0

I've made a simple code to make multiple inserts on the database:

 <?php
if (isset($_POST['numb']) && isset($_POST['email1'])) {
  $error = false;
  $numb = $_POST['numb'];
  for ($i = 1; $i <= $numb; $i++) {
    if (!isset($_POST['email' . $i])) {
      $error = true;
    }
  }
  if ($error == false) {
    include 'config.php';
    try {
      $connection = new PDO($dsn, $user, $pass);
      $suc1 = true;
    } catch (PDOException $e) {
      echo $e->GetMessage();
      $suc1 = false;
    }
    if ($suc1 == true) {
      $sql = "INSERT INTO alunos(email, emailKey) VALUES ";
      for ($i = 1; $i <= $numb; $i++) {
        $BAMBAM[$i] = '(:email' . $i . ', :emailkey' . $i . ')';
        $FELIPEFRANCO[$i] = sha1(microtime() . $_POST['email'. $i]);
        if ($i != $numb) {
          $BAMBAM[$i] = $BAMBAM[$i] . ',';
        }
        $sql = $sql . $BAMBAM[$i];
      }
      $insert = $connection->prepare($sql);
      for ($i = 1; $i <= $numb; $i++) {
        $param1 = 'email' . $i;
        $value1 = $_POST['email' . $i];
        $param2 = 'emailkey' . $i;
        $value2 = $FELIPEFRANCO[$i];
        echo '<script>alert("' . $param1 . ' -> ' . $value1 . '")</script>';
        $insert->bindParam($param1, $value1, PDO::PARAM_STR);
        $insert->bindParam($param2, $value2, PDO::PARAM_STR);
      }
      try {
        $insert->execute();
        $suc2 = true;
      } catch (PDOException $e) {
        echo  $e->GetMessage();
        $suc2 = false;
      }
      echo $sql;
    } else {
      header('Location: addAlunosForm.php?error=internal');
    }
  } else {
    header('Location: addAlunosForm.php?error=fill');
  }
} else {
  header('Location: addAlunosForm.php?error=fill');
}
?>

There is a test script up there, and, in the alert, it says exactly thiis:

email1 -> 1@gmail.com
email2 -> 2@gmail.com
email3 -> 3@gmail.com

But in the databse, it inserts the 3rd value 3 times:

3
NULL
3@gmail.com
901d4043642394ca30ea83688d944987d266b698
NULL
NULL

4
NULL
3@gmail.com
901d4043642394ca30ea83688d944987d266b698
NULL
NULL

5
NULL
3@gmail.com
901d4043642394ca30ea83688d944987d266b698
NULL
NULL

Details:

  • $numb is the number of inserts
  • tlckpl
    • 59
    • 1
    • 8
    • 1
      Where is `execute`? – u_mulder Jun 08 '17 at 20:08
    • Try to execute the last query that, that may help you to debug every time you do an insert: https://stackoverflow.com/questions/7716785/get-last-executed-query-in-php-pdo – xsami Jun 08 '17 at 20:13
    • @u_mulder I thought that it wasnt necessary to post the execute, I'll update with the full code now... – tlckpl Jun 08 '17 at 20:23

    0 Answers0