I want to update my database using php ajax modal. When updating the relevant field { $('#main_id').val(data.id); } don't pass an id to the update query therefor an insertion occurs without executing the updating query.
console log details when trying to update
I tried to solve this but I couldn't. without updating the existing data it inserts a new record
here is my index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ohmsp");
$query = "SELECT * FROM tbl_main_category ORDER BY cat_Id DESC";
$result = mysqli_query($connect, $query);
?>
<div id="employee_table">
<table class="table table-bordered">
<tr> <th width="70%">Employee id</th>
<th width="70%">Employee Name</th>
<th width="15%">Edit</th>
<th width="15%">View</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr> <td><?php echo $row["cat_Id"]; ?></td>
<td><?php echo $row["category_name"]; ?></td>
<td><input type="button" name="edit" value="Edit" id="<?php echo $row["cat_Id"]; ?>" class="btn btn-info btn-xs edit_data" /></td>
<td><input type="button" name="view" value="view" id="<?php echo $row["cat_Id"]; ?>" class="btn btn-info btn-xs view_data" /></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
</body>
</html>
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Employee Details</h4>
</div>
<div class="modal-body" id="employee_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="add_data_Modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">PHP Ajax Update MySQL Data Through Bootstrap Modal</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<label>Enter Employee Name</label>
<input type="text" name="category_name" id="category_name" class="form-control" />
<br />
<input type="hidden" name="main_id" id="main_id" />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#add').click(function(){
$('#insert').val("Insert");
$('#insert_form')[0].reset();
});
$(document).on('click', '.edit_data', function(){
console.log('test')
var main_id = $(this).attr("id");
console.log(main_id)
$.ajax({
url:"fetch.php",
method:"POST",
data:{main_id:main_id},
dataType:"json",
success:function(data){
console.log(data)
$('#category_name').val(data.category_name);
console.log(data.category_name)
$('#main_id').val(data.id);
console.log(data.id)
$('#insert').val("Update");
$('#add_data_Modal').modal('show');
}
});
});
insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ohmsp");
if(!empty($_POST))
{
$output = '';
$message = '';
$category_name = mysqli_real_escape_string($connect, $_POST["category_name"]);
if($_POST["main_id"] != '')
{
$query = "
UPDATE tbl_main_category
SET category_name='$category_name' WHERE cat_Id='".$_POST["main_id"]."'";
$message = 'Data Updated';
}
else
{
$query = "
INSERT INTO tbl_main_category(category_name)
VALUES('$category_name');
";
$message = 'Data Inserted';
}
fetch.php
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "ohmsp");
if(isset($_POST["main_id"]))
{
$query = "SELECT * FROM tbl_main_category WHERE cat_Id = '".$_POST["main_id"]."'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo json_encode($row);
}
?>
You have Fetched the value from $('#main_id').val(data.id) instead of $('#main_id').val(data.cat_Id);
You have fetched value of id instead of cat_Id
Related
I know there are lots of similar posts but nothing really helps me. I'm trying to run a PHP function in Bootstrap Modal with two parameters, one of the parameter is a row ID that needs to go from jQuery.
I can send it and display it in a div id but how can I convert this parameter for a PHP function?
jQuery
$(document).ready(function() {
$("a").click(function(){
var hrefs = $(this).attr("href");
$("#modal_form").attr('action',hrefs);
var ids = hrefs.split("=").pop();
$("#sid").html(ids);
});
});
Bootstrap Modal
<!-- Update Record Modal -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="updateModalLabel">Update Translation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="translation.php" id="modal_form" method="post">
<div class="modal-body">
<div id="sid"></div> /* I'm getting the right ID here*/
<?php selectedTranslation($dbh, $ids); ?> /*I need to run this function*/
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" name="update" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
php function
function getAllTranslationById($dbh, $id){
...
<?php
$sqlSelect = "SELECT * FROM xxxx";
$result = mysqli_query($dbh, $sqlSelect);
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_text'] ?>" readonly="readonly"></td>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_context'] ?>" ></td>
<td><img alt="Link" src="images/edit.png" title="Update this row"></td>
</tr>
<?php }?>
</table>
<?php }
php function
function selectedTranslation($dbh, $sid){
....
<?php
$sqlSelect = "SELECT * FROM xxxx ";
$result = mysqli_query($dbh, $sqlSelect);
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_text'] ?>" readonly="readonly"></td>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_context'] ?>" ></td>
</tr>
<?php }?>
</table>
<?php }?>
Its just impossible like the way you want
So what you can do instead?
Use Ajax.
<div class="modal-body">
<div id="sid"></div> /* I'm getting the right ID here*/
<div id="ajaxResult"></div>
</div>
// JS Codes
$(document).ready(function() {
$("a").click(function(){
var sid = ""; // set your `sid` here
$.ajax({
url: "/url_here", //url to your PHP page
type: "post",
data: {id: sid},
success: function(data) {
$("#ajaxResult").html(data); //result html
}
});
});
});
I am developing a CRUD function based on bootstrap and php. If click edit button, popup windows will be shown and data can edit and update. If click delete button, popup windows will be shown with data but only allow to confirm delete . I dont know why if run it individually only contains one part of code, the program is running properly. But if put both functions code together, only edit function work, and delete function will not shown any data in the popup windows. Also it is strange that when click confirm delete, it is not direct to delete sql statement (delcatsql.php), but direct to update sql(editcatsql.php). Can advice what is wrong?? Thanks!
**manage_categories.php**
<tbody>
<?php
require_once 'source/db_connect.php';
$sql = "SELECT * FROM category";
$result = mysqli_query($link, $sql);
$i=0;
if ($result->num_rows > 0) {
//output data of each row
while ($row = $result->fetch_assoc()) {
$i = $i + 1;
?>
<tr>
<td><?php echo $row['catid']; ?></td>
<td><?php echo $row['catname']; ?> </td>
<td> <button type="button" id="editcatbtn" class="btn btn-primary
editcatbtn">edit</button> </td>
<td> <button type="button" id="delcatbtn" class="btn btn-danger delcatbtn"
>Delete</button> </td>
</tr>
<?php }
}
?>
<script>
$(document).ready(function () {
$(' .delcatbtn').on('click', function() {
$('#delcatmodel').modal('show');
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function() {
return $(this).text();
}).get();
console.log(data);
$('#catid').val(data[0]);
$('#catname').val(data[1]);
});
});
</script>
<script>
$(document).ready(function () {
$(' .editcatbtn').on('click', function() {
$('#editcatmodel').modal('show');
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function() {
return $(this).text();
}).get();
console.log(data);
bootstrap
$('#catid').val(data[0]);
$('#catname').val(data[1]);
});
});
</script>
</tbody>
</table>
</div>
<?php
//Categpry Form
include_once("editcatmodel.php");
include_once("delcatmodel.php");
include_once("editcategory.php");
?>
</body>
**editcatmodel.php**
<!-- edit Model -->
<div class="modal fade" id="editcatmodel" tabindex="-1" role="dialog" aria-
labelledby="exampleModalLabel2" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel2">Edit Category</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="editcatsql.php" method="POST">
<div class="modal-body">
<input type="hidden" name="editcatid" id="catid">
<div class="form-group">
<label>Category Name</label>
<input type="text" name="editcatname" id="catname" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="submit" name="editcategory" class="btn btn-primary">Edit</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.modal -->
editcatsql.php
<?php
include_once 'source/session.php';
require_once 'source/db_connect.php';
?>
<?php
$username = 'root';
password = '';
$dsn = 'mysql:host=localhost; dbname=pos';
$link = mysqli_connect("localhost", "root", "", "pos");
if (isset($_POST['editcategory'])) {
$tempcatname = $_POST[('editcatname')];
$tempcatid = $_POST[('editcatid')];
// write edit query
$sql = "UPDATE category SET catname='$tempcatname' WHERE catid='$tempcatid'" ;
$result = $conn->query($sql);
if(! $result )
{
die('Could not update data: ' . mysql_error());
}
header('location: manage_categories.php');
}
?>
**delcatmodel.php**
<!-- Delete Model -->
<div class="modal fade" id="delcatmodel" tabindex="-1" role="dialog" aria-
labelledby="exampleModalLabel2" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel2">Confirm Delete Category?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="delcatsql.php" method="POST">
<div class="modal-body">
<input type="hidden" name="delcatid" id="catid">
<div class="form-group">
<label>Category Name</label>
<input type="text" name="delcatname" id="catname" class="form-control" disabled>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="deletecategory" class="btn btn-primary">Delete2</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.modal -->
delcatsql.php
<?php
include_once 'source/session.php';
require_once 'source/db_connect.php';
?>
<?php
$username = 'root';
$password = '';
$dsn = 'mysql:host=localhost; dbname=pos';
$link = mysqli_connect("localhost", "root", "", "pos");
if (isset($_POST['deletecategory'])) {
$tempcatname = $_POST[('delcatname')];
$tempcatid = $_POST[('delcatid')];
// write delete query
//$sql = "delete from category where catid='$tempcatid'" ;
$sql = "delete from category where catid='$tempcatid'" ;
$result = $conn->query($sql);
if(! $result )
{
die('Could not update data: ' . mysql_error());
}
header('location: manage_categories.php');
}
?>
Im really confused now please help
... This is the edit/update part which you will edit chosen user. The problem is i think $row or array is empty. The problem is that part. Im accepting any advice to my code to make it better.
Output
This is the output when i click edit button
update.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="uprec.php">
<?php
if(isset($_POST["borrower_id"])){
$output = '';
$connect = mysqli_connect("localhost", "root", "", "librarydb");
$query = "SELECT * FROM tbl_books WHERE id = '".$_POST["borrower_id"]."'";
$result = mysqli_query($connect, $query);
echo "Connected ";
while($row = mysqli_fetch_array($result)){
echo "fetch success";
}
echo "fetch failed";
}
else{
echo "Not Connected";
}
?>
<input type="submit" name="update" id="update" value="UPDATE" class="btn btn-success" />
</form>
</body>
</html>
database.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="script/livesearch.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<a class="navbar-brand" href="#">Home</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Books</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Transactions</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Accounts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="logout.php">Logout</a>
</li>
</ul>
</div>
</nav>
<?php
if(!empty($_SESSION)) {
?>
<div class="container p-3">
<h1 class="">Library Database</h1>
<hr><br>
<form>
<div class="input-group ">
<div class="input-group-prepend">
<span class="input-group-text">Search</span>
</div>
<input type="text" name="search_text" id="search_text" class="form-control" />
</div>
</form>
<br />
<button type="button" class="btn btn-primary mb-3" data-toggle="modal" data-target="#addbook_modal">Add Book</button>
<div id="result"></div>
</div>
<hr>
<?php
}else echo '<div class="alert alert-danger alert-dismissible fade show">
<strong>Login Required!</strong> You needed to be login first before you can access the database.
Go back to login
</div>';
?>
</body>
</html>
<script>
$(document).ready(function() {
$('#addbook_form').on("submit", function(event) {
event.preventDefault();
if ($('#booktitle').val() == "") {
alert("Book Title is required");
} else if ($('#category').val() == '') {
alert("Category is required");
} else if ($('#author').val() == '') {
alert("Author is required");
} else if ($('#publishername').val() == '') {
alert("Publisher Name is required");
} else if ($('#datepublished').val() == '') {
alert("Date Published is required");
} else if ($('#copies').val() == '') {
alert("Copies is required");
} else {
$.ajax({
url: "insert.php",
method: "POST",
data: $('#addbook_form').serialize(),
beforeSend: function() {
$('#addbtn').val("Inserting");
},
success: function(data) {
$('#addbook_form')[0].reset();
$('#addbook_modal').modal('hide');
$('#result').html(data);
}
});
}
});
});
$(document).on('click', '#editbtn', function() {
var borrower_id = $(this).attr("id");
$.ajax({
url: "update.php",
method: "POST",
data: {
borrower_id: borrower_id
},
success: function(data) {
$('#borrower_detail').html(data);
$('#editbook_modal').modal('show');
console.log(data);
}
});
});
</script>
<div id="addbook_modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Book</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form method="POST" id="addbook_form">
<div class="form-group">
<label>Book Title:</label>
<input type="text" name="booktitle" id="booktitle" class="form-control" placeholder="Title of the Book">
</div>
<div class="form-group">
<label>Category:</label>
<select name="category" id="category" class="custom-select">
<option>Art</option>
<option>English</option>
<option>Math</option>
<option>Science</option>
<option>Filipino</option>
</select>
</div>
<div class="form-group">
<label>Author:</label>
<input type="text" name="author" id="author" class="form-control" placeholder="Author of the Book">
</div>
<div class="form-group">
<label>Publisher Name:</label>
<input type="text" name="publishername" id="publishername" class="form-control" placeholder="Name of the Publisher">
</div>
<div class="form-group">
<label>Date Published</label>
<input type="date" name="datepublished" id="datepublished" class="form-control" placeholder="Date of Publication">
</div>
<div class="form-group">
<label>Copies</label>
<input type="number" name="copies" id="copies" class="form-control" placeholder="Number of Copies">
</div>
<div class="form-group">
<button id="addbtn" class="btn btn-success">Add</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="editbook_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Book Details</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="borrower_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
fetch.php
<?php
session_start();
include ('connection.php');
if(!empty($_SESSION)) {
$output = '';
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM tbl_books
WHERE booktitle LIKE '%".$search."%'
OR category LIKE '%".$search."%'
OR author LIKE '%".$search."%'
OR copies LIKE '%".$search."%'
OR publishername LIKE '%".$search."%'
OR datepublished LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM tbl_books ORDER BY id DESC
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="table-responsive" id="employee_table">
<table class="table table-bordered">
<thead>
<tr>
<th>Book Title</th>
<th>Category</th>
<th>Author</th>
<th>Publisher Name</th>
<th>Date Published</th>
<th>Copies</th>
<th>Action</th>
</tr>
</thead>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["booktitle"].'</td>
<td>'.$row["category"].'</td>
<td>'.$row["author"].'</td>
<td>'.$row["publishername"].'</td>
<td>'.$row["datepublished"].'</td>
<td>'.$row["copies"].'</td>
<td><button type="submit" class="btn btn-success btn-sm" id="editbtn">Edit</button>
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
}else echo '<div class="alert alert-danger alert-dismissible fade show">
<strong>Login Required!</strong> You needed to be login first before you can access the database.
Go back to login
</div>';
?>
Currently
$_POST["borrower_id"]
is always "editbtn" all the time. So query always returns zero entries.
Your problem is this
<button type="submit" class="btn btn-success btn-sm" id="editbtn">Edit</button>
and this should probably something like this
<button type="submit" class="btn btn-success btn-sm" id="editbtn" bookid='.$row['id'].'>Edit</button>
$row['id'] depends on whatever your id field is named.
Also you have to change
var borrower_id = $(this).attr("id");
to
var borrower_id = $(this).attr("bookid");
This should work.
Imagine I have 3 data in my tbl_customer then If I click the button view, the modal will show with the data's. It's working if the button I clicked has data, Then the problem is, if the button has no data the modal didn't show. But I want to show the modal even I have no data in my button. Please help me out of this problem, thankyou!
Button: <button type="button" onclick="return chk('.$row['id'].')" class="btn btn-warning btn-xs">Add features</button>
Here's the code:
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>'
<?php
$db = mysqli_connect("localhost", "root", "", "psbr");
$rooms_f = mysqli_query($db, "SELECT * FROM room_f");
while($row = mysqli_fetch_assoc($rooms_f)) { ?>
<button type="button" onclick="return chk('.$row['id'].')" class="btn btn-warning btn-xs">Add features</button>
<?php } ?>
function chk(id)
{
var roomid = document.getElementById('text_id_' + id).value;
var dataString = 'roomid='+ roomid;
$.ajax({
type: "post",
url: "fetch_single3.php",
data:dataString,
cache:false,
success: function(data){
$("#modal_features").hide();
$("#modal_sample").slideDown();
$("#modal_sample").html(data);
}
});
return false;
}
fetch_single3
<?php
$db = mysqli_connect('localhost', 'root', '', 'psbr');
$rooms = mysqli_query($db, "SELECT * FROM rooms");
$roomid = $_POST['roomid'];
$query = mysqli_query($db, "SELECT * FROM room_f WHERE room_id='$roomid'");
?>
<link rel="stylesheet" type="text/css" href="css/feature-design.css">
<div id="modal_sample">
<h4 class="h4" style="margin: 3%;">Room Features</h4>
<button class="btn btn-info button">Add Feature</button>
<table id="features_table">
<tr>
<th width="20%">ID</th>
<th width="49%">Feature</th>
<th>Action</th>
</tr>
<?php while ($row = mysqli_fetch_array($query)) { ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['feature']; ?></td>
<td><button class="btn btn-warning btn-xs">Update Feature</button> <button class="btn btn-warning btn-danger btn-xs ">Delete feature</button></td>
</tr>
<div class="add_modal" id="add_modal">
<h4 style="margin: 5%; ">Add Feature</h4>
<hr>
<label style="margin: 1%;">Enter Feature name</label>
<input type="text" id="text_featurename" name="text_featurename">
<input type="hidden" id="text_featureid" name="text_featureid" value="<?php echo $row['room_id']; ?>">
<input type="submit" name="submit" value="Submit" onclick="return add()" id="submit">
<button class="btn btn-default cbtn_addm">Close</button>
</div>
<?php } ?>
</table>
<button type="button" id="btn_c"class="btn_c">Close</button>
</div>
I've fetched rows from MySQL and looped it with Bootstrap modal and I've made a form in modal from which the data is being sent to PHP script (update.php) with the help of ajax. But in return I am getting the output of last row only.
I need to get the record of specific student with its unique ID.
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
while($row = mysqli_fetch_assoc($query_run)){
$id = $row['id'];
$name = $row['name'];
$rollno = $row['rollno'];
$contact = $row['contact'];
$address = $row['address'];
echo "<tr>";
echo '<td>' . $name . '</td>';
echo '<td>' . $rollno . '</td>';
echo '<td>' . $contact . '</td>';
echo '<td>' . $address . '</td>';
echo "<td><button class='btn btn-link btn-custom dis' data-toggle='modal' data-target='#myModal$id'>
EDIT</button> </td>";
echo '</tr>';
?>
<div class="modal fade" id="myModal<?php echo $id; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="name" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="rollno" value="<?php echo $rollno; ?>">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="contact" value="<?php echo $contact; ?>">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="address"><?php echo $address; ?></textarea>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php }
}?>
</tbody>
</table>
</body>
</html>
JS:
$(document).ready(function(){
var values, url;
$('#updateValues').submit(function(e){
e.preventDefault();
values = $(this).serialize();
url = $(this).attr('action');
$.post(url, values, function(data){
$('#results').html(data);
});
});
});
Update.php:
<?php
if(isset($_POST['name'])&&isset($_POST['rollno'])&&isset($_POST['contact'])&&isset($_POST['address'])){
$id = $_POST['id'];
$name = $_POST['name'];
$rollno = $_POST['rollno'];
$contact = $_POST['contact'];
$address = $_POST['address'];
echo "$id $name $rollno $contact $address";
}else{
echo 'ERROR!';
}
?>
This is not tested/debugged but refactor your code similar to this:
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
$out = '
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
';
while($row = mysqli_fetch_assoc($query_run)){
$out .= '<tr class="trID_' .$row['id']. '">';
$out .= '<td class="td_name">' . $row['name'] . '</td>';
$out .= '<td class="td_rollno">' . $row['rollno'] . '</td>';
$out .= '<td class="td_contact">' . $row['contact'] . '</td>';
$out .= '<td class="td_address">' . $row['address'] . '</td>';
$out .= "<td><button class='td_btn btn btn-link btn-custom dis'>EDIT</button> </td>";
$out .= '</tr>';
}
$out .= '</tbody></table>
echo $out;
?>
<script>
$(document).ready(){
$('.td_btn').click(function(){
var $row = $(this).closest('tr');
var rowID = $row.attr('class').split('_')[1];
var name = $row.find('.td_name').val();
var rollno = $row.find('.td_rollno').val();
var contact = $row.find('.td_contact').val();
var address = $row.find('.td_address').val();
$('#frm_id').val(rowID);
$('#frm_name').text(name);
$('#frm_rollno').text(rollno);
$('#frm_contact').text(contact);
$('#frm_address').text(address);
$('#myModal').modal('show');
});
});//END document.ready
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="frm_name">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="frm_rollno">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="frm_contact">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="frm_address"></textarea>
</div>
<input type="hidden" name="frm_id">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php
}
}
?>
Notes:
(1) Create the entire table in a variable, then output the variable all at once.
(2) You only need one modal, not one modal for each table row. Therefore, remove modal creation from inside while loop.
(3) Use jQuery to:
(a) detect button click in row
(b) get table data for that row
(c) populate fields in modal
(d) display modal
You are using Bootstrap, which uses jQuery, so it makes sense to use jQuery to do this.
(4) Using jQuery to get values from table cells vs. input fields:
(a) .text() - from table cells
(b) .val() - from <input> or <textarea>
Here is a jsFiddle Demo you can play with that demonstrates how you can use jQuery to populate the modal depending on the row that was clicked.