递归PHP PDO POST INSERT

时间:2014-04-19 01:33:25

标签: php mysql pdo insert

我的PHP文件的一部分如下。我正在使用PDO与数据库进行通信,并且我正在从HTML表单中接收数据。两个try / catches都以相同的格式布局,但只有第一个try / catch才能正确插入信息。第二个try / catch没有插入任何信息,也没有捕获任何错误。回声显示很好,但NAMES表中没有数据。

如果有人能指出我的错误,我会非常感激。

$thenumdrivers = $_POST['reg_drivers_num'];

//Query for INSERT drivers into DRIVERS table
try{
    echo "Number of drivers being registered: $thenumdrivers!<br>";

    $STH=$DBH->prepare("INSERT INTO `Drivers` (`Account_id`, `Driver_license`, `Driver_name`, `Driver_birthdate`)
    VALUES (:reg_accountid,:drivers_license,:drivers_firstname,:drivers_dob)");
    for($i=1;$i<=$thenumdrivers;$i++){
        $STH->execute(array(':reg_accountid'=>$theaccountid,':drivers_license'=>$_POST['drivers_license'.$i],':drivers_firstname'=>$_POST['drivers_firstname'.$i],':drivers_dob'=>$_POST['drivers_dob'.$i]));

        echo "1 Driver added!<br>";
    }
}
catch(PDOException $e){
    $e->getMessage();
}

//Query to INSERT driver names into NAMES table
try{
    echo "Number of drivers being added to Names: $thenumdrivers!<br>";

    $STH=$DBH->prepare("INSERT INTO `Names` (`Account_id`, `Name_first`, `Name_middle`, `Name_last`) VALUES (:reg_accountid,:drivers_firstname,:drivers_middleinit,:drivers_lastname)");
    for($k=1;$k<=$thenumdrivers;$k++){
        $STH->execute(array(':reg_accountid'=>$theaccountid,':drivers_firstname'=>$_POST['drivers_firstname'.$k],':drivers_middleinit'=>$_POST['drivers_middleinit'.$k],':drivers_lastname'=>$_POST['drivers_lastname'.$k]));

        echo "1 Name added!<br>";
    }
}
catch(PDOException $e){
    $e->getMessage();
}

print_r($ _ POST)输出仅用于此部分数据。我只试过注册1个驱动程序。所以其他人的空白是正确的。

Array ( [reg_vehicles_num] => 1 [reg_make1] => make [reg_model1] => model [reg_year1] => 2014 [reg_vin1] => 3 [reg_make2] => [reg_model2] => [reg_year2] => [reg_vin2] => [reg_make3] => [reg_model3] => [reg_year3] => [reg_vin3] => [reg_make4] => [reg_model4] => [reg_year4] => [reg_vin4] => [reg_drivers_num] => 1 [drivers_lastname1] => Tester [drivers_middleinit1] => J [drivers_firstname1] => Fester [drivers_dob1] => 2014-04-01 [drivers_license1] => 0987654321 [drivers_lastname2] => [drivers_middleinit2] => [drivers_firstname2] => [drivers_dob2] => [drivers_license2] => [drivers_lastname3] => [drivers_middleinit3] => [drivers_firstname3] => [drivers_dob3] => [drivers_license3] => [drivers_lastname4] => [drivers_middleinit4] => [drivers_firstname4] => [drivers_dob4] => [drivers_license4] => )

1 个答案:

答案 0 :(得分:0)

好的,我唯一能看到的是,在您发送$_POST['reg_drivers_num']但想要访问$_POST['reg_number_drivers']时,请启用error_reporting(E_ALL)

您可能还希望更好地构建POST输入值并发送一组值,这样您就可以使用foreach循环值而不需要reg_number_drivers值。