0

我有一个将数据存储到 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';

        }

    }
   ?>
4

4 回答 4

1

您可以使用 javascript 来验证和限制表单提交,如下所示。如果 userfile 字段为空,则返回 false。

function validate_form(thisform)
{
    with (thisform)
    {
        if (userfile.value==="")
        {
            return false;
        }
    }
    return true;
}

在你的 for 标签中

<form onsubmit="return validate_form(this)">
于 2013-08-23T07:35:51.057 回答
1
  1. "required"您可以在客户端添加 html5属性。
  2. 您还可以通过检查它的值是否为空来在 JS 中进行验证。为此,您可以使用 javascript 的document.getElementsByName方法,也可以使用 Jquery 的$('#id').val()方法。

PS:我建议您也验证它在服务器端。

于 2013-08-23T07:41:31.597 回答
0

停止页面刷新服务器端是不必要的复杂。这是因为,根据请求-响应模型,用户已经提出了他们的请求。页面刷新几乎发生了。但是您可以做的是使用一些客户端脚本来防止请求被触发。最常见的是,Javascript 非常适合:

function validate()
{
     if($('nameTxt').text() != "" && $('otherTxt').text() != "" ...)
     {
        this.submit();
     }
}

注意:我假设jQuery在我的示例中使用了。人们经常使用带有 javascript 的框架,但这不是必需的。请参阅 JJPA 的无框架选项的答案。

于 2013-08-23T07:36:53.703 回答
0

我已经解决了我的问题。我刚刚为文件类型添加了验证。就是这样。并感谢您的宝贵建议。

于 2013-08-23T07:47:34.430 回答