验证数据&将数据插入mysql

时间:2016-02-16 07:15:46

标签: php jquery mysql ajax

我正在制作一个帮助台页面,我有一个页面可以提高票价。我有形式我想要问题类型&要填写的查询字段必填&验证扩展号的数据。即它应该是没有。只要。 我已经尝试过代码来通过ajax&表单验证但不能执行代码和值没有插入到mysql db中。

请帮助!

Ticket.php

    <?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Raise Ticket</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
        $(document).ready(function() {   
            // Form validation.
            if ($('.validate-issue').val() === '') { $('.issue-error').fadeIn(); }   
            if ($('.validate-query').val() === '') { $('.query-error').fadeIn(); }   
            // Grab form values
            var formData = {
                    'ename'    : $('input[name=ename]').val(),
                    'date'     : $('input[name=date]').val(),   
                    'ext'  : $('input[name=ext]').val(),
                    'issue'    : $('select[name=issue]').val(),
                    'query'     : $('input[name=query]').val(),
                    'upload'       : $('input[name=upload]').val()
                    }; 
            if($('.validate-issue').val().trim()) &&($('.validate-query').val().trim()){
            // Ajax form submit.
            $.ajax({
                type: "POST",
                url: "insertticket.php",
                data: formData,
                success: function()
                {
                alert('Ticket has been raised');
                }                   
            });
            } else { alert('Please enter the mandatory fields'); } });
            });
            </script>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><h1 align="center">Helpdesk-Support</h1></div>
<hr>
<div class="panel-body" align="center">
<h2>Raise Ticket!</h2>
<form class="form-horizontal" role="form" enctype="multipart/form-data" method="post">
    <div class="form-group">
      <label class="control-label col-sm-2" for="text">Name:</label>
      <div class="col-sm-10">
        <input type="text" disabled class="form-control" id="text" name="ename" value="<?php echo ucwords($_SESSION['usr_name']);  ?>">
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="date">Date:</label>
      <div class="col-sm-10">          
        <input type="text"  class="form-control" disabled id="date" name="date" value="<?php date_default_timezone_set("Asia/Calcutta"); echo date('Y-m-d H:i:s')?>">
      </div>
    </div>
<div class="form-group">
      <label class="control-label col-sm-2" for="ext">Extension No.:</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="ext" name="ext" placeholder="Enter Extension No.">
      </div>
    </div>
<div class="form-group">
      <label class="control-label col-sm-2" for="issue">Issue Type:</label>    
<div class="col-sm-10">               
        <select class="form-control" id="validate-issue" name="issue"><span class="issue-error">Enter Issue Type</span>
    <option>Select an option</option>
    <option>Hardware Issue</option>
    <option>Network Issue</option>
    <option>Software Issue</option>
    <option>ERP</option>
    <option>CRM</option>
  </select>
    </div>
</div>
<div class="form-group">
      <label class="control-label col-sm-2" for="query">Query:</label>
      <div class="col-sm-10">
        <textarea rows="5" class="form-control" id="validate-query" name="query" placeholder=" Enter Query here"></textarea><span class="query-error">Enter Detailed Query</span>
      </div>
    </div>
<div class="form-group">
      <label class="control-label col-sm-2" for="text">Upload File:</label>
      <div class="col-sm-10">
        <input type="file" class="form-control" id="filetoupload" name="upload" >
      </div>
    </div>
    <div class="form-group">        
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
      </div>
    </div>
  </form>
</div>
<hr>
<div class="panel-footer" align="center">&copy Copyright <?php echo date("Y");?></div>
</div>
</div>
</body>
</html>

insertticket.php

<?php 
$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password=""; // Mysql password 
$db_name="helpdesk"; // Database name 

// Connect to server and select database.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect"); 

mysqli_select_db($conn,$db_name);


$emp_name = mysqli_real_escape_string($conn, $_POST['ename']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$issue_type = mysqli_real_escape_string($conn, $_POST['issue']);
$query = mysqli_real_escape_string($conn, $_POST['query']);
$ext_no. = mysqli_real_escape_string($conn, $_POST['ext']);
$attachment = mysqli_real_escape_string($conn, $_POST['upload']);

$sqli="select * from user where name='$emp_name'";
$result=mysqli_query($conn,$sqli);
while($row=mysqli_fetch_array($result))
{
$emp_code=$row['emp_code'];
$dept=$row['dept'];
$location=$row['location'];
$emailid=$row['emailid'];
$contact_no.=$row['contact_no.'];
}

$sql="INSERT INTO ticket (ticket_no.,emp_code,emp_name,dept,location,emailid,contact_no.,date,issue_type,query,ext_no.,attachment)
VALUES('','$emp_code','$emp_name','$dept','$location','$emailid','$contact_no.','$date','$issue_type','$query','$ext_no.','$attachment')";
if (mysqli_query($conn,$sql))
  {
echo "Record added";

  }
else
{
die('Error: ' . mysqli_error());
 }

?>

1 个答案:

答案 0 :(得分:0)

  • 仅在首次加载时触发脚本。您可以尝试jQuery的.submit()
  • 我不确定您是否可以通过按名称/类/ ID获取内容来上传文件。
  • .trim()仅用于删除多余的空格,而不是用于检查内容?
  • 您的列名中的这些点(.)到底是什么?
  • 您应该使用$_FILES["upload"]["name"]代替$_POST["upload"]来获取用户附加的文件名
  • 您上传文件的代码在哪里?

您可以尝试使用HTML的required属性:

<input required="true" type="text" disabled class="form-control" id="text" name="ename" value="<?php echo ucwords($_SESSION['usr_name']);  ?>">

为什么我们不在您的情况下尝试.submit()

首先,我们必须通过添加<form>属性为您的id提供唯一的数据属性。

<form id="form-submission" class="form-horizontal" role="form" enctype="multipart/form-data" method="post">

然后为你的剧本:

$(document).ready(function(){

  $("form#form-submission").submit(function(){ /* WHEN THE FORM IS SUBMITTED */

    var formData = new FormData($(this)[0]); /* ALL THE DATA IS IN HERE INCLUDING THE FILE ATTACHED */

    $.ajax({ /* CALL AJAX */
      url: "insertticket.php", /* THE FILE WHERE THE DATA WILL GO */
      type: "POST", /* TYPE OF METHOD TO BE USED TO PROCESS THE DATA */
      data: formData, /* THE DATA TO BE PROCESSED */
      contentType: false, /* TYPE OF DATA TO BE PASSED; FOR FILE PURPOSES THAT IS WHY IT IS SET TO FALSE */
      processData: false, /* PREVENT AUTOMATIC PROCESSING */
      success: function(result){ /* IF DATA IS PROCESSED SUCCESSFULLY */
        alert(result); /* ALERT THE RETURNED DATA FROM inserticket.php */
      }
    });

    return false;

  });

});

您还在使用mysqli_,因此更容易将代码转换为prepared statement

这是你的insertticket.php:

<?php

  $conn = new mysqli("localhost", "root", "", "helpdesk");

  /* CHECK CONNECTION */
  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }

  if($stmt = $con->prepare("SELECT emp_code, dept, location, emailid, contact_no FROM user WHERE name = ?")){ /* PREPARE YOUR QUERY */
    $stmt->bind_param("s", $_POST["ename"]); /* BIND THIS DATA TO YOUR QUERY, REPLACING ? WITH $_POST["ename"]; s STANDS FOR STRING TYPE */
    $stmt->execute(); /* EXECUTE QUERY */
    $stmt->bind_result($emp_code, $dept, $location, $emailid, $contact_no); /* BIND THE RESULTS TO THESE VARIABLES CORRESPONDINGLY */
    $stmt->fetch(); /* FETCH THE RESULT */
    $stmt->close(); /* CLOSE THE PREPARED STATEMENT */
  }

  if($stmt = $con->prepare("INSERT INTO ticket (emp_code, emp_name, dept, location, emailid, contact_no, date, issue_type, query, ext_no, attachment) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")){
    $stmt->bind_param("sssssssssss", $emp_code, $_POST["ename"], $dept, $location, $emailid, $contact_no, $_POST["date"], $_POST["issue"], $_POST["query"], $_POST["ext"], $_FILES["upload"]["name"]);
    $stmt->execute();
    $stmt->close();
    echo 'Record added';
  }

  move_upload_file($_FILES["upload"]["tmp_name"], "/system/uploads/".$_FILES["upload"]["name"]); /* UPLOAD THE FILE TO /system/uploads/ FOLDER; JUST REPLACE YOUR DESIRED DIRECTORY */

?>
  • 请务必查看浏览器控制台日志中的错误
  • 您还应该考虑由用户通过您的代码重命名上传的文件,以便它在您的文件夹和数据库中是唯一的。防止导致覆盖文件的重复文件名