我有一个将数据存储到mysql的表单。它工作正常并且没有错误。当我点击提交按钮时,表单包含名称,价格,类别和图像字段数据完全插入数据库。但是当我错过上传一张它没有提交的图片,但是当我点击提交按钮时,我正在丢失其他文件的所有数据时,页面会令人耳目一新。最后,我怀疑当我错过上传图片时我需要停止刷新。 我的代码是
<form enctype="multipart/form-data" action="#" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<label>Name:</label><input type="text" name="name" id="name" size="25"/><br />
<label >Price:</label><input type="text" name="price" id="price" size="25"/><br />
<label>category:</label>
<?php
$con=mysql_connect("","","");
if(!$con)
{
die('couldnot connect to database'.mysql_error());
}
mysql_select_db("dbname",$con);
$dropdown=0;
$result=mysql_query("select DISTINCT(category) from category") or die("No such table"."<br/><br/>".mysql_error());
while($row=mysql_fetch_array($result))
{
$dropdown.="\r\n<option value='{$row['category']}'>{$row['category']} </option>";
}
?>
<?php echo "<select name= 'category' id='category' style='width:14em;'>".$dropdown."</select>";?><br />
<label style="color:#FFFFFF;font-weight:bold">Description:</label></td><td> <input type="text" name="description" id="des"
size="40"/><br />
<label style="color:#FFFFFF;font-weight:bold">Upload Image:</label></td><td><input name="userfile" type="file" /><br /><br
>
<input type="submit" value="Submit" id="submit" style="color:#2594BA;font-size:18px;text-decoration:none;background:#FFF;
padding:3px;border-radius:5px;padding-left:8px;padding-right:8px;"/><br><div id="errormessage">insert data</div>
</form>
</div>
<?php
if(!isset($_FILES['userfile']))
{
}
else
{
try {
$msg= upload(); //this will upload your image
echo $msg; //Message showing success or failure.
}
catch(Exception $e) {
echo $e->getMessage();
echo 'Sorry, could not upload file';
}
}
// the upload function
function upload() {
if(empty($_FILES['userfile']))
{
die();
}
/*database connection code;*/
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
if( $_FILES['userfile']['size'] < $maxsize) {
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
mysql_connect($host, $user, $pass) OR DIE (mysql_error());
mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());
$sql = "INSERT INTO menu(name,description,price,picture,category)
VALUES
('{$_POST['name']}','{$_POST['description']}','{$_POST['price']}','images/{$_FILES['userfile']['name']}','{$_POST['category']}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg='<p>data successfully inserted into database with id ='. mysql_insert_id().' </p>';
}
else {
$msg='<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is '.$maxsize.' bytes</div>
<div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
' bytes</div><hr />';
}
}
else
$msg="File not uploaded successfully.";
}
else
{
$msg= file_upload_error_message($_FILES['userfile']['error']);
echo $msg;
}
}
// Function to return error message based on error code
function file_upload_error_message($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
?>
答案 0 :(得分:1)
您可以使用javascript验证并限制表单提交,如下所示。如果userfile字段为空,则返回false。
function validate_form(thisform)
{
with (thisform)
{
if (userfile.value==="")
{
return false;
}
}
return true;
}
<form onsubmit="return validate_form(this)">
答案 1 :(得分:1)
"required"
属性。 document.getElementsByName
方法,也可以使用Jquery的$('#id').val()
方法。PS:我建议你也在服务器端进行验证。
答案 2 :(得分:0)
停止页面刷新服务器端是不必要的复杂。这是因为,根据请求 - 响应模型,用户已发出请求。页面刷新几乎发生了。但你可以做的是使用一些客户端脚本来防止请求被激活。最常见的是,Javascript非常适用于此:
function validate()
{
if($('nameTxt').text() != "" && $('otherTxt').text() != "" ...)
{
this.submit();
}
}
注意:我假设在我的示例中使用了jQuery
。人们经常使用带有javascript的框架,但这不是必需的。请参阅JJPA对无框架选项的回答。
答案 3 :(得分:0)
我已经解决了我的问题。我刚刚为文件类型添加了验证。就是这样。 并感谢您提出的宝贵建议。