Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

PHP PDO Insert Usando Loop


Você não precisa vincular suas variáveis. Já fiz isso antes com código semelhante. É difícil dizer o que está dando errado embora. Você recebe uma exceção - em caso afirmativo, qual é?

A única coisa que vejo errado é que você tem sua preparação dentro do loop... deve ser mais como:
try {
         $conn = new PDO("mysql:host=$host;dbname=$dbName", $un, $pw);
         echo 'Connected to database<br>';

        $sql = "INSERT INTO studentData (originallyAddedOn, inputMethod, studentFirst, studentLast, studentStreet, studentCity, studentState, studentZip, studentDOB, studentGender, studentGrade, schoolName, schoolStreet, schoolCity, schoolState, schoolZip, schoolContactName, schoolContactTitle, schoolContactEmail, schoolContactPhone) VALUES (:originallyAddedOn, :inputMethod, :studentFirst, :studentLast, :studentStreet, :studentCity, :studentState, :studentZip, :studentDOB, :studentGender, :studentGrade, :schoolName, :schoolStreet, :schoolCity, :schoolState, :schoolZip, :schoolContactName, :schoolContactTitle, :schoolContactEmail, :schoolContactPhone)";

        // prepare once... exceute many :-)
        $q = $conn->prepare($sql); 

        foreach($studentDataArray as $student) {
            $q->execute($yourDataArray);
            // do other stuff if needed

        }

} catch(PDOException $e) {
  echo $e->getMessage();
}