我試圖上傳一個字段到mysql數據庫。該字段可以通過用戶手動輸入或上傳包含該字段的.csv文件來上傳。手動打字效果很好,但是當我嘗試使用.csv上傳時,它看不到該文件並跳到我的代碼的「其他」部分。這是我的代碼:上傳時看不到.csv文件
<?php
$classname = $_POST['classname'];
$classname = stripslashes($classname);
$classname = mysql_real_escape_string($classname);
$save = $_POST['save'];
$save = stripslashes($save);
$save = mysql_real_escape_string($save);
$myfile = $_POST['myfile'];
$myfile = stripslashes($myfile);
$myfile = mysql_real_escape_string($myfile);
$import = $_POST['import'];
$import = stripslashes($import);
$import = mysql_real_escape_string($import);
if($classname && $save)
{
$choose_db;
$sql="INSERT INTO classes (`class`) VALUES ('$classname')";
$res=mysql_query($sql, $connect) or die (mysql_error());
if ($res)
{
echo "<script type='text/javascript'>
alert('Class added succefully');
window.location='../classes.php'
</script>";
}
else
{
echo "<script type=text/javascript'>
alert('Class not added');
window.location('../classes.php');
</script";
}
}
elseif ($import && $myfile)
{
echo $filename = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0)
{
$thefile=fopen($filename, "r");
while (($thedata = fgetcsv($thefile, 10000, ",")) !== FALSE)
{
$sql_file="INSERT INTO classes (`class`) VALUES ('$thedata[1]')";
$res_file=mysql_query($sql_file, $connect) or die (mysql_error());
if (!$res_file)
{
echo "<script type='text/javascript'>
alert ('Invalid file type!');
window.location = '../classes.php';
</script>
";
}
}
fclose($thefile);
echo "<script type='text/javascript'>
alert ('File Imported Successfully!');
window.location = '../classes.php';
</script>
";
}
}
else
{
echo "<script type='text/javascript'>
alert('Fill the form or choose a CSV file');
window.location='../classes.php'
</script>";
}
?>
這裏是HTML表單
<form class="form-horizontal" method="post" name="addclass" action="popups/saveclass.php">
<div style="margin:5px" class="form-group">
<label class="col-sm-12">New Class Name:</label>
<div class="col-sm-12">
<input type="text" name="classname" class="form-control" placeholder="Class Name" />
</div>
</div>
<center><input type="submit" name="save" value="Save" id="submit" style="width:200px; height:30px; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; color:#002435; font-size:14px; cursor:pointer"/>
</center>
</form>
<form class="form-horizontal" method="post" name="uploadcsv" action="popups/saveclass.php" enctype="multipart/form-data">
<br /><center>Or Upload CSV file</center><br />
<div style="margin:5px" class="form-group">
<div class="col-sm-12">
<input type="file" name="myfile" class="form-control" />
</div>
</div>
<center><input type="submit" name="import" value="Import" style="width:200px; height:30px; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; color:#002435; font-size:14px; cursor:pointer"/></center>
</form>
請把你的HTML表單,所以我們可以看到這如何被髮布。 – Mouser
顯然你知道@Barmar在說什麼。你應該檢查'else'是否存在'$ [FILES]'。 – Mouser
如果他們上傳文件但不填寫'$ import'和'$ myfile'會怎麼樣? – Barmar