我的代码可能出现什么问题?相反,我得到......解析错误:语法错误,意外';'
这是我的示例代码,请你协助我
<form enctype="multipart/form-data" method="POST" action="" >
<input type="file" name="file" /><br />
<input type="submit" value="upload csv" name"submit"/>
</form>
<?php
$connection = mysql_connect("localhost","root","")
or die ("Couldn't connect to server");
$db = mysql_select_db("demo", $connection)
or die ("Couldn't select database");
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !== FALSE)
$firstname = $fileop[0];
$lastname = $fileop[1];
$email = $fileop[2];
$sql= mysql_query("INSERT INTO test (first_name,last_name,email)values('$firstname','$lastname','$email')";
}
if($sql)
{
echo "Hello from PHP.";
}
}
?>
答案 0 :(得分:1)
你的PHP中有一个额外的支撑:
if($sql)
{
echo "Hello from PHP.";
}
} // remove this
此外,您的SQL查询缺少右括号,应该是:
$sql= mysql_query("INSERT INTO test (first_name,last_name,email)values('$firstname','$lastname','$email')");
您收到的语法错误是由于特别是sql查询问题 - 它应该是一个右括号,但却找到了一个分号。
您还应该考虑将if ($sql)
逻辑移到if (isset($_POST['submit']))
块中,因为它只能在该范围内发生。这也可能解决你在Shankar回答的评论中提到的“未定义变量”问题。
还有一点注意......看起来你的while
循环只是循环遍历$firstname = $fileop[0];
行,因为你没有围绕其余逻辑的大括号。你想要这样的东西吗?
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
$processed = false;
while(($fileop = fgetcsv($handle,1000,",")) !== FALSE)
{
$firstname = $fileop[0];
$lastname = $fileop[1];
$email = $fileop[2];
$sql = mysql_query("INSERT INTO test (first_name,last_name,email)values('$firstname','$lastname','$email')");
$processed = true;
}
if($processed)
{
echo "CSV was processed.";
}
else
{
echo "CSV was not processed.";
}
}
else
{
echo "Submission was not found.";
}
答案 1 :(得分:0)
这里还有一个额外的支撑
if($sql)
{
echo "Hello from PHP.";
} // here..... remove it
}
并将您的mysql_query语句更改为
$sql= mysql_query("INSERT INTO test (first_name,last_name,email)values('$firstname','$lastname','$email')");
答案 2 :(得分:0)
你的问题在于:
$sql= mysql_query("INSERT INTO test (first_name,last_name,email)values('$firstname','$lastname','$email')";
这还没有正确关闭。它应该看起来像这样(你错过了结束括号):
$sql= mysql_query("INSERT INTO test (first_name,last_name,email)values('$firstname','$lastname','$email')");