如何为PHP / MySQL循环使用多个预准备语句

时间:2013-12-16 16:49:31

标签: php mysql mysqli

我有一个循环,我从CSV解析行,需要插入新数据或检查现有数据,然后获取新记录或现有记录的ID。我使用准备好的INSERT语句和UNIQUE索引(标记?),然后捕获错误以检查记录是否存在。只使用一个预准备语句,此方法在测试中效果很好。

但是,当我将第二个预处理语句步骤添加到我的循环中时(与上述方法相同,但数据不同),当循环返回到第一个准备好的语句时,我开始收到错误Warning: mysqli_stmt_bind_param() [function.mysqli-stmt-bind-param]: Number of variables doesn't match number of parameters in prepared statement in [absolute path to my page]数据

我有一种感觉,我需要关闭结果集或类似的东西,但我不知道如何在不关闭整个数据库连接的情况下有效地完成它。这是我的代码(它从表单接收CSV文件):

if ($_POST["upload"] == "1") {

    //Connect to the database
    $hostname = xxx;
    $username = xxx;
    $dbname = xxx;
    $password = xxx;

    $dbh = mysqli_connect($hostname,$username,$password,$dbname) or die("Problem connecting: ".mysqli_error());
    $stmt = mysqli_stmt_init($dbh);

    $sql1 = "INSERT INTO tbl_TABC_Locations (LocName,LocAddress,LocCity,LocState,LocZip,LocCounty,LocPhone,LocPermitNo) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE LocID=LAST_INSERT_ID(LocID)"; //UNIQUE = LocPermitNo
    $ps_ChkPermit = mysqli_stmt_prepare($stmt, $sql1);

    $sql2 = "INSERT INTO tbl_TABC_ReportDates (ReportMonth,ReportYear,ReportDateFull) 
    VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE ReportDateID=LAST_INSERT_ID(ReportDateID)"; //UNIQUE = ReportDateFull
    $ps_ChkReportDate = mysqli_stmt_prepare($stmt, $sql2);

    $strFileName = $_POST["filename"];

$row = 0;
if (($handle = fopen($strFileName, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $strPermitNo = trim($data[0]);

        //Clean Location name
        $strLocName = trim($data[1]);
        $strLocName = str_replace('"', "", $strLocName);
        $strLocName = str_replace(";","-", $strLocName);
        $strLocName = addslashes($strLocName);

        if ($ps_ChkPermit) 
        {
          mysqli_stmt_bind_param($stmt, "ssssiiis", $field1, $field2, $field3, $field4, $field5, $field6, $field7, $field8);

          $field1 = $strLocName;
          $field2 = trim(addslashes($data[2]));
          $field3 = trim(addslashes($data[3]));
          $field4 = trim($data[4]);
          $field5 = trim($data[5]);
          $field6 = trim($data[6]);
          $field7 = trim($data[7]);
          $field8 = $strPermitNo;
          mysqli_stmt_execute($stmt);

          $intLocID = mysqli_insert_id($dbh);
        }

        //Clean up report dates
        $strReportDate = trim($data[8]);
        $aryNewDate = explode("/", $strReportDate);
        $strNewYear = $aryNewDate[0];
        $strNewMonth = $aryNewDate[1];

        if ($ps_ChkReportDate) 
        {
          mysqli_stmt_bind_param($stmt, "iis", $field1, $field2, $field3);

          $field1 = $strNewMonth;
          $field2 = $strNewYear;
          $field3 = $strReportDate;

          mysqli_stmt_execute($stmt);

          $intDateID = mysqli_insert_id($dbh);
        }

    }
    echo "Closing file now";
    fclose($handle);
}
mysqli_stmt_close($stmt);
mysqli_close($dbh);
}

0 个答案:

没有答案