我无法理解为什么我的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 */?>
答案 0 :(得分: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);
}
}
答案 1 :(得分:0)
好的,我发现了问题。这不是代码,它是.csv文件。出于某种原因,PHP函数无法正确解码.csv版本的Excel for Mac“逗号分隔值”。但是,如果将.csv导出为“windows逗号分隔(.csv)”,那么它就像魅力一样。
感谢您的帮助。