I have created a website mainly using HTML, CSS, PHP and MYSQL. I have successfully gotten tabledit working on the site, but I am not sure how to add the functionality for dropdown checkboxes. I need it to show as checked if the user has the role and when unchecked to update the MySQL table. I have tried reading the code, but am not real familiar with jquery, ajax or javascript. Are dropdown checkboxes something that can be implemented with this plugin?
ModifyUser.php
<html>
<head>
<title>Modifying Users</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://markcell.github.io/jquery-tabledit/assets/js/tabledit.min.js"></script>
<style>
#sample_data tr > *:nth-child(1) {
display: none;
}
</style>
</head>
<body>
<div class="container">
<h3 align="center">Modifying Users</h3>
<br />
<div class="panel panel-default">
<!-- <div class="panel-heading">Sample Data</div>-->
<div class="panel-body">
<div class="table-responsive">
<table id="sample_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Approval</th>
<th>Roles</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<br />
<br />
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
var dataTable = $('#sample_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"FetchUserTable.php",
type:"POST"
}
});
$('#sample_data').on('draw.dt', function(){
$('#sample_data').Tabledit({
url:'ActionUserTable.php',
dataType:'json',
columns:{
identifier : [0, 'user_id'],
editable:[
[1, 'first_name'],
[2, 'last_name'],
[3, 'email'],
[4, 'admin_approved', '{"1":"Approved","2":"Disapproved"}']
[5, 'role_id'] // THIS SHOULD BE AN EDITABLE DROPDOWN CHECKBOX
]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.action == 'delete')
{
$('#' + data.id).remove();
$('#sample_data').DataTable().ajax.reload();
}
}
});
});
});
</script>
FetchUserTable.php
<?php
//FetchUserTable.php
require_once("SetDBConnection.php");
$column = array("user_id", "first_name", "last_name", "email", "admin_approved", "role_id");
$query = "SELECT users.user_id, users.first_name,
users.last_name, users.email,
users.admin_approved,
users_roles.role_id
FROM users, users_roles GROUP BY user_id;";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE first_name LIKE "%'.$_POST["search"]["value"].'%"
OR last_name LIKE "%'.$_POST["search"]["value"].'%"
OR email LIKE "%'.$_POST["search"]["value"].'%"
OR admin_approved LIKE "%'.$_POST["search"]["value"].'%"
OR role_id LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY user_id ASC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$statement = $connect->prepare($query . $query1);
$statement->execute();
$result = $statement->fetchAll();
$statement->closeCursor(); // Added
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['user_id'];
$sub_array[] = $row['first_name'];
$sub_array[] = $row['last_name'];
$sub_array[] = $row['email'];
$sub_array[] = $row['admin_approved'];
$sub_array[] = $row['role_id'];
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT users.user_id, users.first_name,
users.last_name, users.email,
users.admin_approved,
users_roles.role_id
FROM users, users_roles GROUP BY user_id;";
$statement = $connect->prepare($query);
$statement->execute();
return $statement->rowCount();
}
$output = array(
'draw' => intval($_POST['draw']),
'recordsTotal' => count_all_data($connect),
'recordsFiltered' => $number_filter_row,
'data' => $data
);
echo json_encode($output);
Related
I'm trying to pass a php array to JQuery and set a JQuery array to the php array to use as a source for my JQuery DataTable.
Everything seems to run sound, but when the page renders, I only get the header row displayed. Why is my DataTable not displayed?
What changes should I make so that the DataTable displays and renders properly?
<?php
$con = mysqli_connect("localhost", "root", "", "demo_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM demo_table LIMIT 10";
$result = mysqli_query($con,$sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row;
}
mysqli_free_result($result);
mysqli_close($con);
?>
<html>
<body>
<div class="container">
<table id="my-table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>NumOfSales</th>
<th>SalesCurrent</th>
<th>Sales30Days</th>
<th>Sales60Days</th>
<th>Sales90Days</th>
<th>Sales120Days</th>
<th>TotalSales</th>
<th>ErrorDollarAmount</th>
</tr>
</thead>
</table>
</div>
</body>
<script type="text/javascript">
var information = <?php echo json_encode($data); ?>;
$(document).ready(function () {
$('#my-table').dataTable({
data: information,
columns: [
{ title: 'id' },
{ title: 'Name' },
{ title: 'NumOfSales' },
{ title: 'SalesCurrent' },
{ title: 'Sales30Days' },
{ title: 'Sales60Days' },
{ title: 'Sales90Days' },
{ title: 'Sales120Days' },
{ title: 'TotalSales' },
{ title: 'ErrorDollarAmount' }
]
});
});
</script>
</html>
EDIT
I think I see part of the problem, when I view the page source it shows the below, which comments out all of the php EXCEPTthe php that is being written on screen.
<!-- Code Embed v2.3.2 -->
<?php
$con = mysqli_connect("localhost", "root", "", "demo_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM demo_table LIMIT 10";
$result = mysqli_query($con,$sql);
$data = [];
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row;
}
mysqli_free_result($result);
mysqli_close($con);
?>
Here is the working example for passing the data object to datatable using php json_encode() method
Even you were missing the tbody tag for the data table
http://phpfiddle.org/main/code/izyq-3a7y
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href=" https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<?php
$data = array(
array('id'=>'parvez', 'Name'=>11, 'NumOfSales'=>101),
array('id'=>'alam', 'Name'=>1, 'NumOfSales'=>102),
array('id'=>'phpflow', 'Name'=>21, 'NumOfSales'=>103)
);
?>
<html>
<body>
<div class="container">
<table id="my-table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>NumOfSales</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
<script type="text/javascript">
var information = <?php echo json_encode($data) ?>;
$(document).ready(function () {
console.log(information)
$('#my-table').dataTable({
data: information,
columns: [
{ data: 'id' },
{ data: 'Name' },
{ data: 'NumOfSales' },
]
});
});
</script>
</html>
Changes in your current code should be like below:
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href=" https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<?php
$con = mysqli_connect("localhost", "root", "", "demo_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM demo_table LIMIT 10";
$result = mysqli_query($con,$sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row;
}
mysqli_free_result($result);
mysqli_close($con);
?>
<html>
<body>
<div class="container">
<table id="my-table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>NumOfSales</th>
<th>SalesCurrent</th>
<th>Sales30Days</th>
<th>Sales60Days</th>
<th>Sales90Days</th>
<th>Sales120Days</th>
<th>TotalSales</th>
<th>ErrorDollarAmount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
<script type="text/javascript">
var information = <?php echo json_encode($data) ?>;
$(document).ready(function () {
$('#my-table').dataTable({
data: information,
columns: [
{ data: 'id' },
{ data: 'Name' },
{ data: 'NumOfSales' },
{ data: 'SalesCurrent' },
{ data: 'Sales30Days' },
{ data: 'Sales60Days' },
{ data: 'Sales90Days' },
{ data: 'Sales120Days' },
{ data: 'TotalSales' },
{ data: 'ErrorDollarAmount' }
]
});
});
</script>
</html>
i want to use the tableedit JQuery Plugin. This is a code example. The edit of the table is working. But the delete doesnt work. I get the error:
Tabledit Ajax fail => parsererror : SyntaxError: Unexpected token < in JSON
I dont understand why. I have read some Posts here, but I have the Problem yet.
Here is my code:
<?php
$connect = mysqli_connect("localhost", "root", "root", "testing");
$query = "SELECT * FROM tbl_user ORDER BY id DESC";
$result = mysqli_query($connect, $query);
?>
<html>
<head>
<title>Live Table Data Edit Delete using Tabledit Plugin in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery.tabledit.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Live Table Data Edit Delete using Tabledit Plugin in PHP</h3><br />
<table id="editable_table" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["firstname"].'</td>
<td>'.$row["lastname"].'</td>
</tr>
';
}
?>
</tbody>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#editable_table').Tabledit({
url:'action.php',
columns:{
identifier:[0, "id"],
editable:[[1, 'firstname'], [2, 'lastname']]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.action == 'delete')
{
$('#'+data.id).remove();
}
}
});
});
</script>
<?php
//action.php
$connect = mysqli_connect('localhost', 'root', 'root', 'testing');
$input = filter_input_array(INPUT_POST);
$firstname = mysqli_real_escape_string($connect, $input["firstname"]);
$lastname = mysqli_real_escape_string($connect, $input["lastname"]);
if($input["action"] === 'edit'){
$query = "
UPDATE tbl_user
SET firstname = '".$firstname."',
lastname = '".$lastname."'
WHERE id = '".$input["id"]."'
";
mysqli_query($connect, $query);
}
if($input["action"] === 'delete'){
$query = "
DELETE FROM tbl_user
WHERE id = '".$input["id"]."'
";
mysqli_query($connect, $query);
}
header('Content-type: application/json');
print_r(json_encode($input));
?>
I have requests table that have fields (id, name, date, department, answer) and (req_res1.php) that display all records from the table, I tried to create multiple login to access this form for each department only. I mean in a login form there are username and password and department name and when user choose user, pass and dept., the form display results for only this department. I tried different things but nothing works.
req_res1.php
<?php
$connect = mysqli_connect('localhost', 'root', '', 'test')or die ( mysqli_error($connect) );
$sSQL= 'SET CHARACTER SET utf8';
mysqli_query($connect,$sSQL)
or die ('Can\'t charset in DataBase');
$query = "SELECT * FROM requests ORDER BY id DESC";
$result = mysqli_query($connect, $query);
?>
<html>
<head>
<title>update and delete records</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery.tabledit.min.js"></script>
<style>
thead, tr {
color:black;
font-size: 14px;
font-weight: bold;
border-collapse: collapse;
border: 1.5px solid black;
}
th {
background-color: #66CCFF;
color: white;
border: 2px solid black;
}
</style>
</head>
<body dir="rtl">
<br />
<div id="header" align="center">
<img id="image1" src="img/egate4.png">
<br />
</div>
<div class="container" style="width:1200px;">
<br />
<div class="table-responsive">
<h3 align="center">requests display</h3><br />
<table id="editable_table" class="table table-bordered table-striped">
<thead>
<tr>
<th>request no</th>
<th>name</th>
<th>date of request</th>
<th>department</th>
<th>status</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>'.$row["no"].'</td>
<td>'.$row["name"].'</td>
<td>'.$row["reqdate"].'</td>
<td>'.$row["dept"].'</td>
<td>'.$row["answer"].'</td>
</tr>
';
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#editable_table').Tabledit({
url:'req_res2.php',
columns:{
identifier:[0, "no"],
editable:[[1, 'name'], [2, 'reqdate'], [3, 'dept'],[4, 'answer']]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.req_res2 == 'delete')
{
$('#'+data.id).remove();
}
}
});
});
</script>
req_res2.php
<?php
header ('Content-Type: text/html; charset=UTF-8');
$connect = mysqli_connect('localhost', 'root', '', 'test')or die ( mysqli_error($connect) );
$sSQL= 'SET CHARACTER SET utf8';
mysqli_query($connect,$sSQL)
or die ('Can\'t charset in DataBase');
$input = filter_input_array(INPUT_POST);
$name = mysqli_real_escape_string($connect, $input["name"]);
$no = mysqli_real_escape_string($connect, $input["no"]);
$reqdate = mysqli_real_escape_string($connect, $input["reqdate"]);
$answer = mysqli_real_escape_string($connect, $input["answer"]);
if($input["action"] === 'edit')
{
$query = "
UPDATE requests
SET name = '".$name."',
answer = '".$answer."'
WHERE id = '".$input["id"]."'
";
mysqli_query($connect, $query);
}
if($input["action"] === 'delete')
{
$query = "
DELETE FROM requests
WHERE id = '".$input["id"]."'
";
mysqli_query($connect, $query);
}
echo json_encode($input);
?>
I'm writing 2 queries and the first query is working fine but the 2nd query is not working. Please, Guide me.Thanks.
<table class="table table-bordered table-hover">
<form role="form" method="post" action="">
<div class="tablenav top">
<div class="alignleft actions bulkactions">
<label for="bulk-action-selector-top" class="screen-reader-text">Comment Action</label><select name="comment_status" id="bulk-action-selector-top">
<option value="" name="">Select Option</option>
<option value="Approve" name="Approve">Approve</option>
<option value="unapprove" name="unapprove" class="hide-if-no-js">Unapprove</option>
</select>
<input type="submit" name="submit" id="doaction" class="button action" value="Apply">
</div>
<br class="clear">
</div>
<thead>
<tr>
<th></th>
<th>Id</th>
<th>Author</th>
<th>Comments</th>
<th>Email</th>
<th>Author Url</th>
<th>Status</th>
<th>Date</th>
<th>Post Name</th>
<th>Edit</th>
<th>Delete</th>
<th>Reply</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM comments";
global $connection;
$select_comments = mysqli_query($connection, $query) or die('Could not look up user information; ' . mysqli_error($connection));
while ($row = mysqli_fetch_array($select_comments)) {
$comment_id = $row['comment_id'];
$comment_post_id = $row['comment_post_id'];
$comment_author = $row['comment_author'];
$comment_date = $row['comment_date'];
$comment_email = $row['comment_email'];
$comment_author_url = $row['comment_author_url'];
$comment_content = $row['comment_content'];
$comment_status = $row['comment_status'];
echo "<tr>
<td><input type='checkbox' name='check_list[]' value='$comment_id'></td>
<td>$comment_id</td>
<td>$comment_author</td>
<td>$comment_content</td>
<td>$comment_email</td>
<td>$comment_author_url</td>
<td>$comment_status</td>
<td>$comment_date</td>
</tr>";
}
if (isset($_POST['submit'])) {
global $connection;
global $errors;
$comment_status = $_POST['comment_status'];
$check_box = isset($_POST['check_list']) ? $_POST['check_list'] : '';
// error messages
$missingcheckbox = "<p><stong>Recored box not checked.Please check the checkbox.</strong></p>";
// for name feild
if (!$check_box) {
$errors .= $missingcheckbox;
}
if ($errors) {
$resultMessage = '<div class="alert alert-danger">' . $errors . '</div>';
echo $resultMessage;
} else {
for ($i = 0; $i < count($_POST['check_list']); $i++) {
$id = $_POST['check_list'][$i];
if ($comment_status == 'Approve') {
$query = "UPDATE comments SET comment_status = 'approved' WHERE comment_id = $id";
} elseif ($comment_status == 'Unapprove') {
$query = "UPDATE comments SET comment_status = 'unapproved' WHERE comment_id = $id";
}
if ($approve_comments = mysqli_multi_query($connection, $query)) {
// header ("location: comments.php");
// exit;
$resultMessage = '<div class="alert alert-success">Data has been successfully Updated.<img src="../../assets/img/refresh.png" alt="Edit Client" title="Refresh" style="width:30px; height:30px; border:0;"></div>';
echo $resultMessage;
} else {
$resultMessage = '<div class="alert alert-warning">ERROR: Unable to excecute:' . $query . ' . ' . mysqli_error($connection) . '</div>';
echo $resultMessage;
}
}
}
}
?>
</tbody>
</table>
The first query is working fine but 2nd query is not working.I have problem in this code below:-
if($comment_status =='Approve'){
$query = "UPDATE comments SET comment_status = 'approved' WHERE comment_id = $id";
}elseif($comment_status =='Unapprove'){
$query = "UPDATE comments SET comment_status = 'unapproved' WHERE comment_id = $id";
}
Case matters when comparing two strings to be the same
<option value="unapprove"
^^^
and
elseif($comment_status =='Unapprove'){
^^^
$id its a variable and you are putting there as string. Example:
<?php
$a = "Hello ";
$b = $a . "World!"; // "Hello World!"
$a = "Hello ";
$a .= "World!"; // "Hello World!"
?>
You must do the same.
This question already has answers here:
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 11 months ago.
Good day, I've seen a couple of threads with similar questions but I can't seem to implement the suggestions on my practice project.
is there any way I can add a function where my selected items can be deleted at once?
Here are my codes.
select.php
<?php
$connect = mysqli_connect("localhost", "root", "root", "appointments");
$output = '';
$sql = "SELECT * FROM appointments ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="5%">Checkbox</th>
<th width="10%">Id</th>
<th width="40%">Name</th>
<th width="40%">Email</th>
<th width="40%">Address</th>
<th width="10%">phoneNumber</th>
<th width="10%">appointmentTime</th>
<th width="10%">appointmentDate</th>
<th width="50%">message</th>
<th width="10%">delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
</td>
<td><input type="checkbox" /></td>
<td>'.$row["id"].'</td>
<td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
<td class="email" data-id2="'.$row["id"].'" contenteditable>'.$row["email"].'</td>
<td class="address" data-id2="'.$row["id"].'" contenteditable>'.$row["address"].'</td>
<td class="phoneNumber" data-id2="'.$row["id"].'" contenteditable>'.$row["phoneNumber"].'</td>
<td class="appointmentTime" data-id2="'.$row["id"].'" contenteditable>'.$row["appointmentTime"].'</td>
<td class="appointmentDate" data-id2="'.$row["id"].'" contenteditable>'.$row["appointmentDate"].'</td>
<td class="message" data-id2="'.$row["id"].'" contenteditable>'.$row["message"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-danger btn_delete">Delete</button></td>
</tr>
';
}
}
else
{
$output .= '<tr>
<td colspan="10"><center><p style="color:red">No Data Found</p></center></td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
Here's the delete function for a single row.
<?php
$connect = mysqli_connect("localhost", "root", "root", "appointments");
$sql = "DELETE FROM appointments WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
?>
Here's my display page.
<?php
require("config.php");
if(empty($_SESSION['user']))
{
header("Location: success.php");
die("Redirecting to index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Simple Sidebar - Start Bootstrap Template</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/simple-sidebar.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div id="wrapper">
<!-- Sidebar -->
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand">
<a href="#">
Hope Medi Clinic
</a>
</li>
<li>
Logout
</li>
<li>
Main Website
</li>
</ul>
</div>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Appointments</h3><br />
<div id="live_data"></div>
Toggle Menu
</div>
</div>
<!-- /#page-content-wrapper -->
</div>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
/* ............. */
$(document).on('blur', '.name', function(){
var id = $(this).data("id1");
var name = $(this).text();
edit_data(id, name, "name");
});
$(document).on('blur', '.email', function(){
var id = $(this).data("id2");
var email = $(this).text();
edit_data(id, email, "email");
});
$(document).on('blur', '.address', function(){
var id = $(this).data("id2");
var address = $(this).text();
edit_data(id, address, "address");
});
$(document).on('blur', '.phoneNumber', function(){
var id = $(this).data("id2");
var phoneNumber = $(this).text();
edit_data(id, phoneNumber, "phoneNumber");
});
$(document).on('blur', '.appointmentTime', function(){
var id = $(this).data("id2");
var appointmentTime = $(this).text();
edit_data(id, appointmentTime, "appointmentTime");
});
$(document).on('blur', '.appointmentDate', function(){
var id = $(this).data("id2");
var appointmentDate = $(this).text();
edit_data(id, appointmentDate, "appointmentDate");
});
$(document).on('blur', '.message', function(){
var id = $(this).data("id2");
var message = $(this).text();
edit_data(id, message, "message");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id3");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
</body>
</html>
It will be cleaner and more professional to send an array of ids to your php file as suggested by earlier answers:
<input name="ids[]" value="<?php echo $id; ?>" type="checkbox">
...then make just one trip to the database to delete multiple rows.
if (
empty($_POST['ids'])
// || array_filter($_POST['ids'], function($v) { return !ctype_digit($v); })
) {
exit('Missing/Invalid data submitted'); // be deliberately vague
}
$connect = new mysqli("localhost", "root", "root", "appointments");
$count = count($_POST['ids']);
$stmt = $connect->prepare(
sprintf(
"DELETE FROM appointments WHERE id IN (%s)",
implode(',', array_fill(0, $count, '?')) // e.g if 3 ids, then "?,?,?"
)
);
$stmt->bind_param(str_repeat('i', $count), ...$_POST['ids']);
$stmt->execute();
printf('Deleted %d row(s)', $stmt->affected_rows());
This resembles a similar post of mine: SELECT with dynamic number of values in IN()
I'm not sure exactly how you are sending the data from the HTML to the PHP page in this example, so I will give you a generic simple implementation and hopefully you can figure out how to work it into your project.
HTML:
Using checkboxes, you can send multiple values as an array to a php script like so.
<form action="delete.php" method="POST">
<input name="delete[]" value="id_of_row" type="checkbox">
<input name="delete[]" value="id_of_another_row" type="checkbox">
<button type="submit">Submit</button>
</form>
This will send an array of whatever is in the value attribute of each box that is checked. You would then be able to delete every row that was checked with the following php script.
PHP:
<?php
$connect = mysqli_connect("localhost", "root", "root", "appointments");
foreach($_POST['delete'] as $id){
$sql = "DELETE FROM appointments WHERE id = '" . $id . "';
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
}
?>
This should be what you need to somehow implement into your existing project so that you can delete multiple rows at once.
You should be using array for this.
<td><input type="checkbox" name='check[]' value=".$row['id']." /></td>
and in delete function you should be doing something like this.
<?php
$connect = new mysqli("localhost", "root", "root", "appointments");
$totalCheckboxChecked = sizeof($_POST['check']);
for($i=0;$i<$totalCheckboxChecked;$i++)
{
$idToDelete = $check[$i];
$sql = "DELETE FROM appointments WHERE id = $idToDelete";
$result=$connect->query($sql);
}