Php 如何使用jQueryAjax传递表单数据以在数据库中插入数据?
我有四张桌子,分别是stud、country、master、state和master。 主要的问题是,我的表单由许多不同的字段组成,比如文本框、单选按钮、下拉列表和图像文件,所以我真的很困惑。 我无法在数据库中插入数据。请帮帮我。我试了很多次,但都不起作用。提前谢谢你的帮助。 home.php页面中的模态Php 如何使用jQueryAjax传递表单数据以在数据库中插入数据?,php,jquery,ajax,bootstrap-modal,Php,Jquery,Ajax,Bootstrap Modal,我有四张桌子,分别是stud、country、master、state和master。 主要的问题是,我的表单由许多不同的字段组成,比如文本框、单选按钮、下拉列表和图像文件,所以我真的很困惑。 我无法在数据库中插入数据。请帮帮我。我试了很多次,但都不起作用。提前谢谢你的帮助。 home.php页面中的模态 <div class="container"> <div class="modal fade" id="add_data_modal" role="dialog">
<div class="container">
<div class="modal fade" id="add_data_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-heading" style="margin-top:30px;text-align:center">
<button class="close" data-dismiss="modal" style="margin-right:20px;font-weight:bold;">x</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-user"></span> Add Student</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form class="form-horizontal" name="form" id="form" method="post" action="<?php $_PHP_SELF?>" enctype="multipart/form-data">
<label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>
<input type="text" class="form-control" name="name" id="name" pattern="[a-zA-Z]{3,}" title="Name should only contain letters and atleast 3 letters" required />
</div>
<div class="form-group">
<label for="no"><span class="glyphicon glyphicon-phone"></span><b> Mobile No: </b></label><label id="p2">*</label>
<input type="text" class="form-control" name="mob_no" id="mob_no" pattern="[0-9]{10}" title="Mobile number should be of 10 digits" required />
</div>
<div class="form-group">
<label for="dob"><span class="glyphicon glyphicon-calendar"></span><b> Birth Date: </b></label><label id="p3">*</label>
<input type="date" class="form-control" name="dob" required />
</div>
<div class="form-group">
<label for="add"><span class="glyphicon glyphicon-map-marker"></span><b> Address: </b></label><label id="p4">*</label>
<textarea rows="4" cols="33" class="form-control" name="add" id="add" required></textarea>
</div>
<div class="form-group">
<label for="photo"><span class="glyphicon glyphicon-camera"></span><b> Photo: </b></label><label id="p5">*</label>
<input type="file" name="photo" id="photo" required />
</div>
<div class="form-group">
<label for="gen"><b> Gender: </b></label><label id="p6">*</label><br/>
<input type="radio" name="gender" id="gender" value="M" required="required">Male
<input type="radio" name="gender" id="gender" value="F" required="required">Female
</div>
<div class="form-group">
<label for="cntry"><span class="glyphicon glyphicon-map-marker"></span><b> Country: </b></label><label id="p7"> *</label>
<?php
$country="SELECT * from country_master_academic";
$res= $conn->query($country);
if($res->num_rows>0)
{
echo '<select name="country" id="country" class="form-control" required>';
echo '<option value="">Select</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["country_code"].'>'.$row['country_name'].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
</div>
<div class="form-group">
<label for="state"><span class="glyphicon glyphicon-map-marker"></span><b> State: </b></label><label id="p8">*</label>
<?php
$state = "SELECT * from master_state";
$res=$conn->query($state);
if($res->num_rows>0)
{
echo '<select name="state" id="state" class="form-control" required>';
echo '<option value="">Select</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["state_code"].'>'.$row["state_name"].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
</div>
<div class="form-group">
<label for="city"><span class="glyphicon glyphicon-map-marker"></span><b> City: </b></label><label id="p9">*</label>
<?php
$city="SELECT * from master_city";
$res=$conn->query($city);
if($res->num_rows>0)
{
echo '<select name="city" id="city" class="form-control" required>';
echo '<option value="">Select</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["city_code"].'>'.$row["city_name"].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
</div>
<div class="form-group">
<button type="submit" name="save" id="save" class="btn btn-info" onclick="validate()">Save</button>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-danger" type="button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
我的insert.php页面
<?php
include("connection.php");
if(!empty($_POST))
{
$output = '';
$name = $_POST['name']);
$mob = $_POST['mob_no']);
$dob = $_POST['dob']);
$add = $_POST['add']);
$photo = $_FILES['photo']['name']);
$gender = $_POST['gender']);
$cn = $_POST['country']);
$st = $_POST['state']);
$ct = $_POST['city']);
$qrycn= mysqli_query($conn,"select country_code from country_master_academic where country_name=' ".$cn." ' ");
$row = mysqli_fetch_array($qrycn);
$country = $row['country_code'];
$qryst=mysqli_query($conn,"select state_code from master_state where state_name='".$st."'");
$row = mysqli_fetch_array($qryst);
$state = $row['state_code'];
$qryct= mysqli_query($conn,"select city_code from master_city where city_name='".$ct."'");
$row = mysqli_fetch_array($qryct);
$city = $row['city_code'];
$query = "INSERT INTO stud (stud_name, mobile, dob,address,photo,gender,country,state,city) VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$country', '$state', '$city')";
if (mysqli_query($conn, $query)) {
$target_dir="images/";
$target_file=$target_dir.basename($_FILES["photo"]["name"]);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file)){
echo '<script language="javascript">';
echo 'alert("Image and data Inserted Successfully")';
echo '</script>';
} else {
echo '<script language="javascript">';
echo 'alert("Cannot upload")';
echo '</script>';
}
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot insert record")';
echo '</script>';
}
$output .= '<label class="text-success">Data Inserted</label>';
$output .= '
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Mobile</th>
<th>Birthdate</th>
<th>Address</th>
<th>Photo</th>
<th>Gender</th>
<th>Country</th>
<th>State</th>
<th>City</th>
</tr>
';
$result= mysqli_query($conn,"select * from stud s, country_master_academic c, master_state st, master_city ct where s.country=c.country_code and s.state=st.state_code and s.city=ct.city_code");
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td><a href="update.php?no='.$row["stud_no"].'"><button name="edit" value="Edit" style="font-weight:bold;" class="btn btn-warning"><span class="glyphicon glyphicon-edit"></span> Edit</button></a></td>
<td><button type="submit" style="font-weight:bold;" name="delete" id='.$row["stud_no"].' class="btn btn-danger delete_data"><span class="glyphicon glyphicon-trash"></span> Delete</button></td>
<td><button type="submit" style="font-weight:bold;" name="view" id='.$row["stud_no"].' class="btn btn-success view_data" data-target="#modalDelete" data-toggle="modal"><span class="glyphicon glyphicon-user"></span> View</button></td>
</tr>
';
}
$output .= '</table>';
}
echo $output;
}
?>插入的新代码:
谢谢大家对我的帮助
<?php
include("connection.php");
if(!empty($_POST))
{
$output = '';
$name = $_POST['name'];
$mob = $_POST['mob_no'];
$dob = $_POST['dob'];
$add = $_POST['add'];
$photo = $_FILES['photo']['name'];
$gender = $_POST['gender'];
$cn = $_POST['country'];
$st = $_POST['state'];
$ct = $_POST['city'];
$query = "INSERT INTO stud(stud_name, mobile, dob,address,photo,gender,country,state,city)VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$cn', '$st', '$ct ')";
if (mysqli_query($conn, $query)) {
$target_dir="images/";
$target_file=$target_dir.basename($_FILES["photo"]["name"]);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file)){
echo '<script language="javascript">';
echo 'alert("Image Inserted Successfully")';
echo '</script>';
} else {
echo '<script language="javascript">';
echo 'alert("Cannot upload")';
echo '</script>';
}
echo '<script language="javascript">';
echo 'alert("Data Inserted Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot insert record")';
echo '</script>';
}
}
?>插入的新代码:
谢谢大家对我的帮助
<?php
include("connection.php");
if(!empty($_POST))
{
$output = '';
$name = $_POST['name'];
$mob = $_POST['mob_no'];
$dob = $_POST['dob'];
$add = $_POST['add'];
$photo = $_FILES['photo']['name'];
$gender = $_POST['gender'];
$cn = $_POST['country'];
$st = $_POST['state'];
$ct = $_POST['city'];
$query = "INSERT INTO stud(stud_name, mobile, dob,address,photo,gender,country,state,city)VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$cn', '$st', '$ct ')";
if (mysqli_query($conn, $query)) {
$target_dir="images/";
$target_file=$target_dir.basename($_FILES["photo"]["name"]);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file)){
echo '<script language="javascript">';
echo 'alert("Image Inserted Successfully")';
echo '</script>';
} else {
echo '<script language="javascript">';
echo 'alert("Cannot upload")';
echo '</script>';
}
echo '<script language="javascript">';
echo 'alert("Data Inserted Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot insert record")';
echo '</script>';
}
}
?>请使用您的表单id提交表单数据,并通过ajax和alertdata进行调试
请使用您的表单id提交表单数据,并通过ajax和alertdata进行调试
好的,让我列出html中的所有错误
<label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>
换成
$output = '';
$name = $_POST['name'];
$mob = $_POST['mob_no'];
$dob = $_POST['dob'];
$add = $_POST['add'];
$photo = $_FILES['photo']['name'];
$gender = $_POST['gender'];
$cn = $_POST['country'];
$st = $_POST['state'];
$ct = $_POST['city'];
然后移除
$qrycn= mysqli_query($conn,"select country_code from country_master_academic where country_name=' ".$cn." ' ");
$row = mysqli_fetch_array($qrycn);
$country = $row['country_code'];
$qryst=mysqli_query($conn,"select state_code from master_state where state_name='".$st."'");
$row = mysqli_fetch_array($qryst);
$state = $row['state_code'];
$qryct= mysqli_query($conn,"select city_code from master_city where city_name='".$ct."'");
$row = mysqli_fetch_array($qryct);
$city = $row['city_code'];
并将insert更改为
$query = "INSERT INTO stud (stud_name, mobile, dob,address,photo,gender,country,state,city) VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$cn', '$st', '$ct')";
在js中,应该像这样使用FormData
<label for="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>
$('.insert_data').click(function(){
var vname = $("#name").val();
var vmob = $("#mob_no").val();
var vdob = $("#dob").val();
var vadd = $("#add").val();
var vphoto = $("#photo").val();
var vgender = $("#gender").val();
var vcountry = $("#country").val();
var vstate = $("#state").val();
var vcity = $("#city").val();
var fd=new FormData();
fd.append('name',vname);
fd.append('mob_no',vmob);
fd.append('dob',vdob);
fd.append('add',vadd);
fd.append('photo',vphoto);
fd.append('gender',vgender);
fd.append('country',vcountry);
fd.append('state',vstate);
fd.append('city',vcity);
$.ajax({
url:"insert.php",
method:"post",
data: fd,
success: function(data){
$('#form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#stud_insert').html(data);
}
});
});
好的,让我列出html中的所有错误
<label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>
换成
$output = '';
$name = $_POST['name'];
$mob = $_POST['mob_no'];
$dob = $_POST['dob'];
$add = $_POST['add'];
$photo = $_FILES['photo']['name'];
$gender = $_POST['gender'];
$cn = $_POST['country'];
$st = $_POST['state'];
$ct = $_POST['city'];
然后移除
$qrycn= mysqli_query($conn,"select country_code from country_master_academic where country_name=' ".$cn." ' ");
$row = mysqli_fetch_array($qrycn);
$country = $row['country_code'];
$qryst=mysqli_query($conn,"select state_code from master_state where state_name='".$st."'");
$row = mysqli_fetch_array($qryst);
$state = $row['state_code'];
$qryct= mysqli_query($conn,"select city_code from master_city where city_name='".$ct."'");
$row = mysqli_fetch_array($qryct);
$city = $row['city_code'];
并将insert更改为
$query = "INSERT INTO stud (stud_name, mobile, dob,address,photo,gender,country,state,city) VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$cn', '$st', '$ct')";
在js中,应该像这样使用FormData
<label for="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>
$('.insert_data').click(function(){
var vname = $("#name").val();
var vmob = $("#mob_no").val();
var vdob = $("#dob").val();
var vadd = $("#add").val();
var vphoto = $("#photo").val();
var vgender = $("#gender").val();
var vcountry = $("#country").val();
var vstate = $("#state").val();
var vcity = $("#city").val();
var fd=new FormData();
fd.append('name',vname);
fd.append('mob_no',vmob);
fd.append('dob',vdob);
fd.append('add',vadd);
fd.append('photo',vphoto);
fd.append('gender',vgender);
fd.append('country',vcountry);
fd.append('state',vstate);
fd.append('city',vcity);
$.ajax({
url:"insert.php",
method:"post",
data: fd,
success: function(data){
$('#form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#stud_insert').html(data);
}
});
});
这是我在Laravel项目中提交表单数据的代码,如下所示:
//Save new category
$(".frm-add-category").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: '/dashboard/category',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
success:function(data){
//Refresh the grid
alert(data.success);
},
error: function(e){
alert(e.error);
}
});
});
这是我在Laravel项目中提交表单数据的代码,如下所示:
//Save new category
$(".frm-add-category").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: '/dashboard/category',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
success:function(data){
//Refresh the grid
alert(data.success);
},
error: function(e){
alert(e.error);
}
});
});
那么你有什么错误吗?哪一部分不起作用?乍一看,你的代码似乎应该可以工作。你说的“不工作”是什么意思?在控制台中是否有任何错误?脚本错误还是PHP错误?没有错误?@DirkScholten没有,先生。。。它没有显示任何错误。@AliSheikhpour没有错误。。。就在我单击save之后,modal gets closedData没有被插入,我想我的jquery有问题,或者我没有正确插入。所以您有没有收到任何错误?哪一部分不起作用?乍一看,你的代码似乎应该可以工作。你说的“不工作”是什么意思?在控制台中是否有任何错误?脚本错误还是PHP错误?没有错误?@DirkScholten没有,先生。。。它没有显示任何错误。@AliSheikhpour没有错误。。。就在我点击save之后,modal gets closedData没有被插入,我想我的jquery有问题,或者我没有正确地插入u,但我想说一件事,在数据库中我存储了国家代码,而不是国家名称,所以在插入时我必须存储国家代码,在显示时应该显示国家名称。其余所有记录都将被插入。只有国家、州和城市未被插入请检查数据库表螺柱数据类型和长度。非常感谢,但我想说一件事,在数据库中我存储了国家代码,而不是国家名称,因此在插入时我必须存储国家代码,在显示时应显示国家名称。其余所有记录都将被插入。仅国家、州和城市未获得insertedPlease使用数据库表stud datatype和length进行检查。在insert.php中,您不需要在数据库中搜索国家代码、州代码或城市代码,因为您已经将它们传递给php,因此,删除3个查询,并在insert语句中使用post值并将它们保存到数据库$query=insert到stud stud_name、mobile、dob、address、photo、gender、country、state、city值'$name','$mob','$dob','$add','$photo','$gender','$cn','$st','$ct';查看编辑后的帖子,其工作状态和所有数据都存储在数据库中。在你的insert.php中,你不需要搜索数据库中的国家代码、州代码或城市代码,因为你已经将它们传递给了php,所以删除3个查询,在你的insert语句中使用帖子值并将它们保存到数据库$query=insert-INTO-stud_-name,mobile,dob,地址、照片、性别、国家、州、城市值“$name”、“$mob”、“$dob”、“$add”、“$photo”、“$gender”、“$cn”、“$st”、“$ct”;查看编辑后的文章,其工作和所有数据都存储在数据库中