php - 停止表单提交?

标签 php javascript

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

        }

    }
   ?>

最佳答案

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

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

在你的 for 标签中

<form onsubmit="return validate_form(this)">

关于php - 停止表单提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18397173/

相关文章:

javascript - 在 Meteor 中如何在服务器端渲染模板?

javascript - 如果所有值都等于 0,则删除数组中的系列

php - 在 Laravel 5.1 中找不到 "Class ' app\Http\Controllers\Controller'

php - 查找最大的连续时间段集

php - ImageMagick - 将多页 PDF 转换为一张图像

javascript - 动态使用部分来管理字段

javascript - Vue : standard way to hide template if no data or loading

php - Laravel Eloquent 查询哪里喜欢关系?

php - Codeigniter:将 activeRecord 与手动查询相结合?

javascript - 绝对定位的元素在离开容器边界时变得不可见