6

我在使用 PDO 将多条记录插入数据库时​​遇到问题。我可以成功添加一条记录,但是一旦添加foreach循环,它就会失败。在阅读了有关此的其他一些 SO 问题后,我相信我需要“绑定”我的变量,尽管我对正确的语法完全感到困惑。

这是我创建的原始函数:

<? function addToDatabase () {
    //Get All Variables
    $timestamp = date("Y-m-d H:i:s");
    $schoolName = $_SESSION['schoolName'];
    $schoolStreet = $_SESSION['schoolStreet'];
    $schoolCity = $_SESSION['schoolCity'];
    $schoolState = $_SESSION['schoolState'];
    $schoolZip = $_SESSION['schoolZip'];
    $schoolContactName = $_SESSION['schoolContactName'];
    $schoolContactTitle = $_SESSION['schoolContactTitle'];
    $schoolContactPhone = $_SESSION['schoolContactPhone'];
    $schoolCsontactEmail = $_SESSION['schoolContactEmail'];
    $inputMethod = $_SESSION['inputMethod'];

    $studentDataArray = $_SESSION['studentDataArray'];

    $studentFirstNameField = $_SESSION['studentFirstNameField'];
    $studentLastNameField = $_SESSION['studentLastNameField'];
    $studentStreetField = $_SESSION['studentStreetField'];
    $studentCityField = $_SESSION['studentCityField'];
    $studentStateField = $_SESSION['studentStateField'];
    $studentZipcodeField = $_SESSION['studentZipcodeField'];
    $studentDOBField = $_SESSION['studentDOBField'];
    $studentGenderField = $_SESSION['studentGenderField'];
    $studentGradeField = $_SESSION['studentGradeField'];

    //Connnect to Database
    $host = 'myHost';
    $un = 'myUsername';
    $pw = 'myPassword';
    $db_name = 'myTable';

    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)";

        foreach ($studentDataArray as $student){
            $q = $conn->prepare($sql);
            echo $student[$studentFirstNameField]."<br>";
            $q->execute(array(  ':originallyAddedOn'=>$timestamp,
                            ':inputMethod'=>$inputMethod,
                            ':studentFirst'=>$student[$studentFirstNameField],
                            ':studentLast'=>$student[$studentLastNameField],
                            ':studentStreet'=>$student[$studentStreetField],
                            ':studentCity'=>$student[$studentCityField],
                            ':studentState'=>$student[$studentStateField],
                            ':studentZip'=>$student[$studentZipField],
                            ':studentDOB'=>$student[$studentDOBField],
                            ':studentGender'=>$student[$studentGenderField],
                            ':studentGrade'=>$student[$studentGradeField],
                            ':schoolName'=>$schoolName,
                            ':schoolStreet'=>$schoolStreet,
                            ':schoolCity'=>$schoolCity,
                            ':schoolState'=>$schoolState,
                            ':schoolZip'=>$schoolZip,
                            ':schoolContactName'=>$schoolContactName,
                            ':schoolContactTitle'=>$schoolContactTitle,
                            ':schoolContactEmail'=>$schoolContactEmail,
                            ':schoolContactPhone'=>$schoolContactPhone));           
            }
            // close the database connection
            $dbh = null;
        }
        catch(PDOException $e) {
            echo $e->getMessage();
            }
    }

$studentDataArray外观与此类似:

 0 => //student 1
    array
      [0] => 'Joe' //First
      [1] => 'Smith' //Last
      [2] => '101 Main St' //Street
      [3] => 'Boston' //City
      [4] => 'MA' //State
      [5] => '01234' //Zip
      [6] => '2000-01-01' //Date of Birth
      [7] => 'Male' //Gender
      [8] => '12'  //Grade

 1 => //Student 2
    array
      [0] => 'Jane'
      [1] => 'Smith'
      [2] => '99 Main St'
      [3] => 'Boston'
      [4] => 'MA'
      [5] => '01234'
      [6] => '2000-02-02'
      [7] => 'Female'
      [8] => '10'


更新: 对于那些感兴趣的人,这是我修复错误后的最终功能:

<? function addToDatabase ($dataArray) {

    //Connnect to Database
    $host = 'myHost';
    $un = 'myUsername';
    $pw = 'myPassword';
    $db_name = 'myTable';    

    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)";
        $q = $conn->prepare($sql);

        foreach ($dataArray as $student){
            $a = array (':originallyAddedOn'=>$student['timestamp'],
                        ':inputMethod'=>$student['inputMethod'],
                        ':studentFirst'=>$student['studentFirst'],
                        ':studentLast'=>$student['studentLast'],
                        ':studentStreet'=>$student['studentStreet'],
                        ':studentCity'=>$student['studentCity'],
                        ':studentState'=>$student['studentState'],
                        ':studentZip'=>$student['studentZip'],
                        ':studentDOB'=>$student['studentDOB'],
                        ':studentGender'=>$student['studentGender'],
                        ':studentGrade'=>$student['studentGrade'],
                        ':schoolName'=>$student['schoolName'],
                        ':schoolStreet'=>$student['schoolStreet'],
                        ':schoolCity'=>$student['schoolCity'],
                        ':schoolState'=>$student['schoolState'],
                        ':schoolZip'=>$student['schoolZip'],
                        ':schoolContactName'=>$student['schoolContactName'],
                        ':schoolContactTitle'=>$student['schoolContactTitle'],
                        ':schoolContactEmail'=>$student['schoolContactEmail'],
                        ':schoolContactPhone'=>$student['schoolContactPhone']);

            if ($q->execute($a)) {          
                // Query succeeded.
                } else {
                    // Query failed.
                    echo $q->errorCode();
                    }
            // close the database connection
            $dbh = null;
            echo "Insert Complete!";
        }
        }
        catch(PDOException $e) {
            echo $e->getMessage();
            }
    }
4

2 回答 2

7

你不需要绑定你的变量。我以前用类似的代码做过这个。很难说出了什么问题。你有例外吗 - 如果有,那是什么?

我唯一看到的错误是您在循环中进行了准备……应该更像:

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();
}
于 2013-01-05T01:18:13.543 回答
2

对于循环,请执行以下操作(PDO 或其他支持准备好的语句的数据库客户端库):

  1. 准备 SQLINSERT查询。
  2. 绑定变量。
  3. 根据绑定变量循环您的数组,每次迭代执行一次。

利润。

对于基于数组的 PDO 示例,该数组包含要插入到某个表中的数据,该表需要名为option.

首先将一些数据插入数据库:

$options = [
    ['option' => "Insert Option A " . uniqid()],
    ['option' => "Insert Option B " . uniqid()],
    ['option' => "Insert Option C " . uniqid()],
];

在其他地方,让我们假设拥有该$options数组并关心数据库交互。这需要一个连接:

$conn = new PDO('mysql:dbname=test;host=localhost', 'testuser', 'test');

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);

现在让我们准备插入查询。在问题中使用命名参数,确保这也适用于编号参数:

$stmt = $conn->prepare('INSERT INTO config (`OPTION`) VALUES (:OPTION);');

现在让我们在这里将命名参数绑定到一个变量。请注意,该变量带有前缀(此处为insert)。这实际上是option输入数组中键的别名:

$stmt->bindParam(':OPTION', $insert_option);

所以现在从上面的编号列表中,要点 1.) 准备 SQLINSERT查询。和 2.) 绑定变量。已经完成。

只剩下$options数组上的循环以插入值:

foreach ($options as $insert) {
    extract($insert, EXTR_PREFIX_ALL, 'insert');
    $stmt->execute();
}

利用extract允许以别名方式基于输入数组一次设置多个变量,无需太多麻烦。

完整的例子:

$options = [
    ['option' => "Insert Option A " . uniqid()],
    ['option' => "Insert Option B " . uniqid()],
    ['option' => "Insert Option C " . uniqid()],
];

$conn = new PDO('mysql:dbname=test;host=localhost', 'testuser', 'test');

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);

# 1. Prepare    
$stmt = $conn->prepare('INSERT INTO config (`OPTION`) VALUES (:OPTION);');

# 2. Bind
$stmt->bindParam(':OPTION', $insert_option);

# 3. Loop & Execute
foreach ($options as $insert) {
    extract($insert, EXTR_PREFIX_ALL, 'insert');
    $stmt->execute();
}
于 2013-01-05T02:18:54.970 回答