将多个记录插入mysql和mysql_affected_rows()

时间:2011-12-28 10:11:31

标签: php mysql

我正在从表单上传csv。我正在尝试使用mysql_affected_rows来确定它是否成功。数据正在上传到表中,但mysql_affected_rows未评估为true。请帮忙:

<?php
session_start();
$idnewtest1 = $_GET['idnewtest1'];

      move_uploaded_file($_FILES["fileCSV"]["tmp_name"],
      "quiz/" . $_FILES["fileCSV"]["name"]);

    $objConnect = mysql_connect("localhost","root","...") or die(mysql_error()); // Conect to MySQL
    $objDB = mysql_select_db("testing");

$objCSV = fopen("quiz/".$_FILES["fileCSV"]["name"], "r");
fgetcsv($objCSV, 1000, ","); // skip first row

        while (($objArr = fgetcsv($objCSV, 1000, ",")) !== FALSE) {
        $strSQL = "INSERT INTO ex_question1 ";
        $strSQL .="(id,test_name,q_nr,....) ";
        $strSQL .="VALUES ";
        $strSQL .="('0','".$idnewtest1."','".$objArr[0]."'....) ";
        $objQuery = mysql_query($strSQL);
    }
    fclose($objCSV);

if (mysql_affected_rows() > 1) {
echo "Import completed.";
}    

?>

3 个答案:

答案 0 :(得分:2)

有多个事务正在通过while循环处理所以多个insert语句, 每个返回1到mysql_affected_row(),

第二件事你使用函数out side while while循环和条件&gt; 1每次mysql_affected_row()返回1时都不会满足bcz .​​..

答案 1 :(得分:2)

执行:


<?php
$affectedRows = 0;
    while (($objArr = fgetcsv($objCSV, 1000, ",")) !== FALSE) {
        $strSQL = "INSERT INTO ex_question1 ";
        $strSQL .="(id,test_name,q_nr,....) ";
        $strSQL .="VALUES ";
        $strSQL .="('0','".$idnewtest1."','".$objArr[0]."'....) ";
        $objQuery = mysql_query($strSQL);
        $affectedRows +=mysql_affected_rows();
    }
    fclose($objCSV);

if ($affectedRows > 1) {
echo "Import completed.";
}    
?>

答案 2 :(得分:1)

您可以使用此INSERT查询

INSERT INTO ex_question1
(id,test_name,q_nr,....)
VALUES (...............),
(...............),
(...............),
(...............);

这将一次性插入所有行