1

我不明白为什么我的 while 循环在插入第一行数据后停止。请帮忙。我正在尝试在 MySql 表中上传 .csv 文件 - 如果数据已经存在,请跳过并转到第二行。

<?php
$dbhost = "xxxx";
$dbname = "xxxx";
$dbuser = "xxxx";
$dbpass = "xxxx";
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());

fgetcsv_PHP();

function fgetcsv_PHP()
{

    if (($handle = fopen("events.csv", "r")) !== FALSE)
    {

        $length = 1000;
        $delimiter = ",";



        while ( ( $data = fgetcsv( $handle) ) !== FALSE )
        {
            // Count number of array elements in $data
            $num = count($data);
            // Print opening table row HTML tag
            $data[5]= strtolower($data[5]);
            $data[11]= "2012-06-22 10:30:40";
            $import="INSERT into candidatedb(event,rec,title,name,surname,email,phone,discip,exper,wheread,comment,stamp) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]')";


            $result = mysql_query("SELECT * from candidatedb WHERE email = '$data[5]' AND surname = '$data[4]'");
            $num_rows = mysql_num_rows ($result);
            echo $num_rows;

            if ($num_rows > 0) {

                echo "Email address: $data[5] already exist </br>"; 
            }

            else {      

                    mysql_query($import) or die(mysql_error());
                    echo "Done! $data[5] inserted<br/>";
            }
        }
        // Close the file pointed to by $handle
        fclose($handle);
    }
}

"Done!<br/> $num record uploaded" 
?>




<?php /*?>
       $import="INSERT into candidatedb(event,rec,title,name,surname,email,phone,discip,exper,wheread,comment,stamp) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]')";

       mysql_query($import) or die(mysql_error());
<?php */?>
4

2 回答 2

0

如果您尝试使用此调试,输出是什么:

fgetcsv_PHP();

function fgetcsv_PHP() {

$length    = 1000;
$delimiter = ",";
if (($handle = fopen("events.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, $length, $delimiter)) !== FALSE)
    {
        echo "read line: ".implode($data, ';')." <br>\n";
    }
    fclose($handle);
}
}
于 2012-07-03T09:16:21.097 回答
0

好的,我发现了问题。它不是 .csv 文件的代码。由于某种原因, php 函数未正确解码 Mac 版 Excel 的 .csv 版本“逗号分隔值”。但是,如果您将 .csv 导出为“windows 逗号分隔 (.csv)”,那么它就像一个魅力。

在此处输入图像描述

谢谢你的帮助。

于 2012-07-03T09:31:40.877 回答