currently I have created a system that can perform multiple delete actions for a list of data rows that fetch from a SQL database and display at dashboard_engineer.php. Each data row contains a delete button. Each row also has a checkbox that enables the user to delete selected data rows. At the bottom of the data rows, there's a button to delete all the selected data rows.
My problem is on multiple delete, lets say, if I select two data rows, (id 4 and 5) it will only delete one ID.
Below is my code
dashboard_engineer2.php
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$team = $_REQUEST['team'];
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid
WHERE ot_report.status = 'yes' AND ot_users.team_id = :team AND report_date BETWEEN :from
AND :to ORDER BY ot_report.report_id DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to,);
$sql -> execute();
if($sql->rowCount() > 0){
echo'
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "10%"><input type="checkbox" id="checkAl"> All</th>
<th width = "3%">id</th>
<th width = "15%">Date</th>
<th width = "25%">Supervisor</th>
<th width = "30%">Task Name</th>
<th width = "10%">Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
}
else {
$color="color:green";
}
$report_id = $row["report_id"];
echo'<tr>';
echo '<td><input type="checkbox" id="checkItem" name="check[]" value="'.$report_id.'"></td>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$row['report_date'].'</td>';
echo '<td>'.$row["fullname"].'</td>';
echo '<td>'.$row["task_name"].'</td>';
echo '<td align="center" style='.$color.'><strong>'.$status.'</strong></td>';
echo '<td align="center">';
echo '<form action = "view_task/view_task.php" method = "post" target="_blank">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-primary">View</button>';
echo '</form>';
echo '</td>';
echo '<td align="center">';
echo "<form action = 'remove2.php' method = 'post' onClick=\"return confirm('Do you want to remove this reports?')\">";
echo '<input type = "hidden" name = "from" value = "'.$from.'">';
echo '<input type = "hidden" name = "to" value = "'.$to.'">';
echo '<input type = "hidden" name = "team" value = "'.$team.'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Remove</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
$i++;
}
echo '<tr>';
echo '<td>';
echo "<form action = 'delete_selected.php' method = 'post'>";
echo '<input type="hidden" id="checkItem" name="check[]" value="'.$report_id.'">';
echo '<button type="submit" class="btn-danger btn-sm">DELETE</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
?>
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++){
$report_id = $checkbox[$i];
$sql = "UPDATE ot_report SET status = 'no' WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>
Can anyone help me to solve this problem? Thanks
OK - the following is based upon the question's code but in order to build a working demo it has been generalised. The important thing here is the use of Javascript to maintain the list of IDs selected ( either by clicking the select-all checkbox or by clicking individual checkboxes. Please ignore the content generated in the form - the dates are spurious and meaningless to this example.
You could copy this and create a test page which should run OK - the PHP that generates the pseudo SQL is simply to display the statements that would be executed and not how it should be executed ( should be as per question, prepared statement )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( isset( $_POST['ids'] ) ){
$items=explode( ',', $_POST['ids'][0] );
foreach($items as $id){
$sql=sprintf('UPDATE ot_report SET status="no" WHERE report_id=%d',$id);
echo $sql . '<br />';
}
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<table>
<?php
for( $i=1; $i <= 10; $i++ ){
/* example data for dates... */
$hrs=mt_rand(1,24);
$mins=mt_rand(0,60);
$secs=mt_rand(0,60);
$month=mt_rand(1,12);
$day=mt_rand(1,28);
$year=mt_rand(2000,2020);
$from=date('y-m-d',mktime($hrs,$mins,$secs,$month,$day,$year));
$to=date('y-m-d',mktime($hrs+3,$mins+20,$secs,$month,$day,$year));
printf('
<tr>
<td><input type="checkbox" name="check[]" value="%1$d" /></td>
<td>Some data %1$d</td>
<td>
<form method="post">
<input type="hidden" name="from" value="%2$s" />
<input type="hidden" name="to" value="%3$s" />
<input type="hidden" name="id" value="%1$d" />
<input type="submit" />
</form>
</td>
</tr>', $i, $from, $to );
}
?>
</table>
<form method='post'>
<input type='checkbox' name='selectall' value='Select-All' />
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='Update selected' />
</form>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
</body>
</html>
Will generate something akin to:
UPDATE ot_report SET status="no" WHERE report_id=10
UPDATE ot_report SET status="no" WHERE report_id=8
UPDATE ot_report SET status="no" WHERE report_id=6
UPDATE ot_report SET status="no" WHERE report_id=4
Quickly trying to adapt this example with your code :
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from=$_REQUEST['from'];
$to =$_REQUEST['to'];
$team=$_REQUEST['team'];
$result='';
$query="SELECT * FROM ot_report
LEFT JOIN ot_users ON ot_report.badgeid=ot_users.badgeid
WHERE ot_report.status='yes' AND ot_users.team_id=:team AND report_date BETWEEN :from AND :to
ORDER BY ot_report.report_id DESC";
$sql=$conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to);
$sql->execute();
if($sql->rowCount() > 0){
echo'
<table class="table-bordered" width="100%">
<thead>
<tr>
<th width="10%"><input type="hidden" name="selectall" value="Select-All">All</th>
<th width="3%">id</th>
<th width="15%">Date</th>
<th width="25%">Supervisor</th>
<th width="30%">Task Name</th>
<th width="10%">Status</th>
<th colspan="2" width="7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row=$sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
} else {
$color="color:green";
}
$report_id=$row["report_id"];
echo'
<tr>
<td><input type="checkbox" name="check[]" value="'.$report_id.'"></td>
<td>'.$report_id.'</td>
<td>'.$row['report_date'].'</td>
<td>'.$row["fullname"].'</td>
<td>'.$row["task_name"].'</td>
<td align="center" style='.$color.'><strong>'.$status.'</strong></td>
<td align="center">
<form action="view_task/view_task.php" method="post" target="_blank">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-primary">View</button>
</form>
</td>
<td align="center">
<form action="remove2.php" method="post" onsubmit="return confirm(\'Do you want to remove this reports?\')">
<input type="hidden" name="from" value="'.$from.'">
<input type="hidden" name="to" value="'.$to.'">
<input type="hidden" name="team" value="'.$team.'">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-danger">Remove</button>
</form>
</td>
</tr>';
$i++;
}
echo '
<tr>
<td>
<form action="delete_selected.php" method="post">
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='DELETE' />
</form>
</td>
</tr>';
}
}
?>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
and
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox=explode( ',', $_POST['ids'][0] );
for($i=0;$i < count($checkbox); $i++){
$report_id=$checkbox[$i];
$sql="UPDATE ot_report SET status='no' WHERE report_id=:report_id";
$query=$conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>
Related
Currently, I created a system that has AJAX function. To be more clear, below is my current process flow:
1) dashboard.php will display 3 select option which is team, time from and time to
2) user need to complete all 3 select option and click button 'search'. At this point where AJAX (range.php).
3) All data row will be listed and each data have a delete button. User can delete data based on data row.
My problem is, the data is not deleted.
Below is my current code.
dashboard.php
<select class="form-control" name="team" id="team">
<option value="">Please select...</option>
<?php foreach ($data as $row2): ?>
<option value= <?php echo $row2["team_id"]; ?> <?php echo (($_GET["team"] ?? '') == $row2["team_id"]) ? 'selected' : ''; ?> ><?php echo $row2["fullname"]; ?></option>
<?php endforeach ?>
</select>
<td width="1%"></td>
</td>
<td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" value = '<?php echo $_GET["from"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" value = '<?php echo $_GET["to"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="10%"><input type="button" name="range" id="range" value="Search" class="btn btn-primary"><td>
</tr>
</table><br>
<div id = "dashboard">
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from").datepicker().attr("autocomplete", "off");;
$("#to").datepicker().attr("autocomplete", "off");;
});
$('#range').click(function(){
var from = $('#from').val();
var to = $('#to').val();
var team = $('#team').val();
if(from != '' && to != '' && team != '')
{
$.ajax({
url:"range.php",
method:"POST",
data:{from:from, to:to, team:team},
success:function(data)
{
$('#dashboard').html(data);
}
});
}
else
{
alert("Please select both team and date range");
}
});
if($('#from').val() && $('#to').val() && $('#team').val()){
$('#range').click();
}
});
</script>
range.php (AJAX)
<?php
require_once "../../../config/configPDO.php";
require_once "../../../config/check.php";
$email = $_SESSION['login_user'];
if(isset($_POST["from"], $_POST["to"], $_POST["team"]))
{
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST['team']."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();
if($sql->rowCount() > 0)
{
echo'
<form method="post" action="">
<div class="row" style="height: 300px; overflow-y: scroll;">
<div class="col-lg-12 grid-margin stretch-card">
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th>id</th>
<th>Date</th>
<th>Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
while($row = $sql->fetch(PDO::FETCH_ASSOC))
{
$datereport = $row['report_date'];
$datereport2 = strtotime($datereport);
$report_date = date('d M Y', $datereport2);
$report_id = $row["report_id"];
echo'<tr>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$report_date.'</td>';
echo '<td align="center">';
echo '<a class="btn-view btn-primary btn-sm" href="view_task/view_task.php?report_id='. $report_id .'" data-toggle="tooltip">View</a></td>';
echo '<td align="center">';
echo '<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">';
echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Delete</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
delete_ajax.php
<?php
require_once '../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$sql = "DELETE FROM ot_report WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php?from='".$_POST["from"]."'&to='".$_POST["to"]."' &team='".$_POST["team"]."'");
?>
Can anyone knows what is the problem? The data cannot deleted!. Help anyone
maybe this is because in the range.php file you have 2 form tags
first is outside while function
<form method="post" action="">
and second one is in while function
<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">
try removing the first one
Ihave a problem when i want to view a data row in details. Below is the flow of the system:
1) At dashboard_engineer.php, there's 3 select options which is team, time from and time to.
2) user need to select 3 select option and press button "Search" to display the result.
3) The result will display at dashboard_engineer2.php.
4) The result will display all data rows and each row contains one View button which can view a data row in detail.
My problem is only in the first data row. When I click button View', it will redirect to dashboard_engineer2.php with empty data. But for the second data and next, I can view the details of selected data.
This only happen only at the first data that display after filtered. Below is my code.
dashboard_engineer.php
<?php
$smt = $conn->prepare("
SELECT *
FROM ot_team t
JOIN ot_users u
ON t.team_id = u.team_id
WHERE u.roles_id = 7
AND u.team_id <> 1
ORDER
BY u.fullname ASC
");
$smt->execute();
$data = $smt->fetchAll();
?>
<form method = 'post' action = 'dashboard_engineer2.php' >
<td width="40%">
<select class="form-control" name="team" id="team" required>
<option value="">Please select...</option>
<?php foreach ($data as $row2): ?>
<option value= <?php echo $row2["team_id"]; ?> ><?php echo $row2["fullname"]; ?></option>
<?php endforeach ?>
</select>
</td>
<td width="1%"></td>
<td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" required></td>
<td width="1%"></td>
<td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" required></td>
<td width="1%"></td>
<td width="10%"><button type="submit" value="Search" class="btn btn-primary" >Send</button><td>
</form>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from").datepicker().attr("autocomplete", "off");;
$("#to").datepicker().attr("autocomplete", "off");;
});
});
</script>
dashboard_engineer2.php
<?php
if(isset($_REQUEST["from"], $_REQUEST["to"], $_REQUEST["team"])){
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$team = $_REQUEST['team'];
$result = '';
$query = "
SELECT *
FROM ot_report r
LEFT
JOIN ot_users u
ON r.badgeid = u.badgeid
WHERE u.team_id = '".$team."'
AND report_date BETWEEN '".$from."' AND '".$to."'
ORDER
BY r.report_id DESC
";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();
if($sql->rowCount() > 0){
echo'
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "10%"><input type="checkbox" id="checkAl"> All</th>
<th width = "3%">id</th>
<th width = "15%">Date</th>
<th width = "30%">Task Name</th>
<th width = "10%">Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$datereport = $row['report_date'];
$datereport2 = strtotime($datereport);
$report_date = date('d M Y', $datereport2);
$report_id = $row["report_id"];
echo'<tr>';
echo '<td><input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'></td>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$report_date.'</td>';
echo '<td>'.$row["task_name"].'</td>';
echo '<td align="center"><strong>'.$row["report_status"].'</strong></td>';
echo '<td align="center">';
echo '<form action = "view_task/view_task.php" method = "post">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-primary">View</button>';
echo '</form>';
echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
echo '<input type = "hidden" name = "from" value = "'.$from.'">';
echo '<input type = "hidden" name = "to" value = "'.$to.'">';
echo '<input type = "hidden" name = "team" value = "'.$team.'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Delete</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
$i++;
}
echo '<tr>';
echo '<td><p align="center"><button type="submit" class="btn-danger btn-sm" name="save">DELETE</button></p></td>';
echo '</tr>';
echo '</form>';
}
else
{
echo '
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "5%">id</th>
<th width = "12%">Date</th>
<th width = "23%">Task Name</th>
<th width = "10%">Status</th>
<th width = "7%">Action</th>
</tr>
<tr>
<td colspan="5">No report found</td>
</tr>';
}
echo '</body></table></div></div>';
}
?>
view_task.php
<?php
require_once "../../../../config/configPDO.php";
require_once "../../../../config/check.php";
if (isset ($_POST['report_id'])) {
$report_id = $_POST['report_id'];
}else if (isset ($_GET['report_id'])) {
$report_id = $_GET['report_id'];
}else {
die ("ID NOT DEFINED");
}
$sql = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid LEFT JOIN ot_team ON ot_team.team_id = ot_users.team_id WHERE report_id = :report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$report_id = $row["report_id"];
$task_name = $row["task_name"];
}
?>
<form action="update_task_name.php" method="POST">
<td><b>Task Name</b></td>
<td colspan = '2'><input type="text" class="form-control" name="task_name" value="<?php echo $task_name; ?>"/></td> //line 50
<input type="hidden" name="report_id" value="<?php echo $report_id ?>">
<td><input type="submit" class="btn btn-primary btn-block" value = "Save" onclick="confirm('Are you sure?')"></td>
</form>
Can anyone help?
I have a problem with my delete function. Before that, I will brief to you about the flow of the system
1) At dashboard_engineer.php, there's 3 select options which is team, time from and time to.
2) user need to select 3 select option and press button "Search" to display the result.
3) The result will display at dashboard_engineer2.php.
4) The result will display all data rows and each row contains one delete button.
My problem is, after I click button delete, it was successful delete but the dashboard_engineer2.php page doesn't display the result that same as point 3 above. The result empty.
What I want is that, after delete, the dashboard_engineer2.php will display the remaining data rows that already filtered before. Below is my code.
dashboard_engineer.php
<?php
$smt = $conn->prepare("SELECT * FROM ot_team INNER JOIN ot_users ON ot_team.team_id = ot_users.team_id WHERE ot_users.roles_id = 7 AND ot_users.team_id <> 1 ORDER BY ot_users.fullname ASC");
$smt->execute();
$data = $smt->fetchAll();
?>
<form method = 'post' action = 'dashboard_engineer2.php' >
<td width="40%">
<select class="form-control" name="team" id="team" required>
<option value="">Please select...</option>
<?php foreach ($data as $row2): ?>
<option value= <?php echo $row2["team_id"]; ?> ><?php echo $row2["fullname"]; ?></option>
<?php endforeach ?>
</select>
</td>
<td width="1%"></td>
<td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" required></td>
<td width="1%"></td>
<td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" required></td>
<td width="1%"></td>
<td width="10%"><button type="submit" value="Search" class="btn btn-primary" >Send</button><td>
</form>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from").datepicker().attr("autocomplete", "off");;
$("#to").datepicker().attr("autocomplete", "off");;
});
});
</script>
dashboard_engineer2.php
<?php
if(isset($_POST["from"], $_POST["to"], $_POST["team"])){
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST["team"]."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();
if($sql->rowCount() > 0){
echo'
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "10%"><input type="checkbox" id="checkAl"> All</th>
<th width = "3%">id</th>
<th width = "15%">Date</th>
<th width = "30%">Task Name</th>
<th width = "10%">Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$datereport = $row['report_date'];
$datereport2 = strtotime($datereport);
$report_date = date('d M Y', $datereport2);
$report_id = $row["report_id"];
echo'<tr>';
echo '<td><input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'></td>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$report_date.'</td>';
echo '<td>'.$row["task_name"].'</td>';
echo '<td align="center"><strong>'.$row["report_status"].'</strong></td>';
echo '<td align="center">';
echo '<form action = "view_task/view_task.php" method = "post">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-primary">View</button>';
echo '</form>';
echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Delete</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
$i++;
}
echo '<tr>';
echo '<td><p align="center"><button type="submit" class="btn-danger btn-sm" name="save">DELETE</button></p></td>';
echo '</tr>';
echo '</form>';
}
else
{
echo '
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "5%">id</th>
<th width = "12%">Date</th>
<th width = "23%">Task Name</th>
<th width = "10%">Status</th>
<th width = "7%">Action</th>
</tr>
<tr>
<td colspan="5">No report found</td>
</tr>';
}
echo '</body></table></div></div>';
}
?>
delete.php
<?php
$report_id = $_POST['report_id'];
$sql = "DELETE FROM ot_report WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer2.php");
?>
Can anyone help me on how to fix this?
this case is the same as the question
PHP / MySQL: Display some error after successfully updated the data
that's because in dashboard_engineer2.php your code will display data from the database if the from, to, team variable is posted.
from delete.php redirect to dashboard_engineer2.php being the get method and the data that was previously posted is missing
change the delete.php code to be like this
<?php
$report_id = $_POST['report_id'];
$from = $_POST['from'];
$to = $_POST['to'];
$team = $_POST['team'];
$sql = "DELETE FROM ot_report WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
// so that the data previously posted is taken
// when redirecting to the dashboard_engineer2.php page
// even though it is a GET method
header("Location: dashboard_engineer2.php?from={$from}&to={$to}&team={$team}");
?>
and there was a slight change in dashboard_engineer2.php to be like this
<?php
// change the initial conditions to be like this
// $_REQUEST will get data if there is data in POST or GET
if(isset($_REQUEST["from"], $_REQUEST["to"], $_REQUEST["team"])){
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$team = $_REQUEST['team'];
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$team."' AND report_date BETWEEN '".$from."' AND '".$to."' ORDER BY ot_report.report_date DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();
if($sql->rowCount() > 0){
echo'
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "10%"><input type="checkbox" id="checkAl"> All</th>
<th width = "3%">id</th>
<th width = "15%">Date</th>
<th width = "30%">Task Name</th>
<th width = "10%">Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$datereport = $row['report_date'];
$datereport2 = strtotime($datereport);
$report_date = date('d M Y', $datereport2);
$report_id = $row["report_id"];
echo'<tr>';
echo '<td><input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'></td>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$report_date.'</td>';
echo '<td>'.$row["task_name"].'</td>';
echo '<td align="center"><strong>'.$row["report_status"].'</strong></td>';
echo '<td align="center">';
echo '<form action = "view_task/view_task.php" method = "post">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-primary">View</button>';
echo '</form>';
echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
echo '<input type = "hidden" name = "from" value = "'.$from.'">';
echo '<input type = "hidden" name = "to" value = "'.$to.'">';
echo '<input type = "hidden" name = "team" value = "'.$team.'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Delete</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
$i++;
}
echo '<tr>';
echo '<td><p align="center"><button type="submit" class="btn-danger btn-sm" name="save">DELETE</button></p></td>';
echo '</tr>';
echo '</form>';
}
else
{
echo '
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "5%">id</th>
<th width = "12%">Date</th>
<th width = "23%">Task Name</th>
<th width = "10%">Status</th>
<th width = "7%">Action</th>
</tr>
<tr>
<td colspan="5">No report found</td>
</tr>';
}
echo '</body></table></div></div>';
}
?>
You can try my code below , sorry if it is not run
delete.php
$from = $_POST["from"];
$to = $_POST["to"];
$team = $_POST["team"];
header("Location: dashboard_engineer2.php?from=$from&to=$to&team=$team");
Then change condition seem like below.
dashboard_engineer2.php
if(isset($_REQUEST["from"], $_REQUEST["to"], $_REQUEST["team"])){
Hope it work well .
I not PHP developer well, But I guess when you redirect on delete.php,
on dashboard_engineer2.php it does not exist $_POST["from"], $_POST["to"], $_POST["team"] params.So if will return false and code on if will not excute, please debug on it.
Solution is you should past it as get parameter when redirect .
i have created one edit form that i am editing my room number and room description and room image etc . based on the category id.
first edit form will fetch the data from database .
example code :
if (isset($_GET['id']))
{
$current_id = $_GET['id'];
$query=mysql_query("select * from room where room_id='$current_id'");
$i = 0;
while($row=mysql_fetch_array($query))
{
$i++;
$room_id=$row['room_id'];
$cat_id=$row['cat_id'];
$room_number=$row['room_no'];
$room_desc=$row['room_desc'];
$room_image=$row['room_image'];
?>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Room Id</th>
<th>Category Type</th>
<th>Room Number</th>
<th>Room Description</th>
<th>Room Image</th>
</tr>
</thead>
<tbody>
<tr class="active">
<td><input type="text" value="<?php echo $room_id; ?>" readonly="readonly" name="room_id"></td>
<td>
<?php
// Slecting cat_id for displaying cat_type on Edit form
$query_room=mysql_query("SELECT * FROM `category` WHERE cat_id in (". $cat_id .")");
while($row=mysql_fetch_array($query_room))
{
$category_name=$row['cat_type'];
$category_id=$row['cat_id'];
echo '<input type="text" value='.$category_name.' readonly="readonly" name="cat_name">';
echo '<input type="hidden" value='.$category_id.' readonly="readonly" name="cat_id">'; // hidden value for cat_id to fetch data from category
$_SESSION['imagesession'] = "data:image/png;base64, base64_encode($room_image)";
}
?>
</td>
<td><input type="text" value="<?php echo $room_number ;?>" name="room_number" required></td>
<td><input type="text" value="<?php echo $room_desc ;?>" name="room_desc" required></td>
<td><input type="image" src="data:image/png;base64,<?php echo base64_encode($room_image);?>" name="myimage" alt="No Photo" title="Click to View in Detail" height="50px" width="50px"/>
<label>Upload Image</label>
<input type="file" id="uploadImage" value="<?php echo base64_encode($room_image);?>" name="image" onChange="PreviewImage();" />
<img id="uploadPreview" style="width: 200px; height: 300px; border-style:none" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<button type="submit" class="btn btn-success" name="update_rooms">Update Rooms</button>
<button type="reset" class="btn btn-danger">Reset</button>
</form>
Getting data and updating in database
if(isset($_POST['update_rooms']))
{
$current_id = $_POST['room_id'];
$room_desc = $_POST['room_desc'];
$room_number = $_POST['room_number'];
$cat_id = $_POST['cat_id'];
// $imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
if(empty($imageData))
{
if($imageData === $existing_category_image)
{
echo '<span style="color:#E02F2F;text-align:center;font-size:30px;padding-left:190px;">Reselect the Image</span>';
return;
}
}
$sql = "UPDATE room SET cat_id='$cat_id', room_no='$room_number', room_desc='$room_desc', room_image='$imageData' WHERE room_id='$current_id'";
//echo "Res".$sql;
$result=mysql_query($sql);
if($result)
{
echo '<span style="color:#E02F2F;text-align:center;font-size:30px;padding-left:190px;">Record Updated Successfully!</span>';
//header("Location: success.php");
} else
{
echo '<span style="color:#E02F2F;text-align:center;font-size:30px;padding-left:250px;">Error Found!.mysql_error()</span>';
}
}
PROBLEM:
1.while editing all fields are updating successfully but come to the image its not working i mean if user is adding new image then its updating in database but if user is editing existing image then null value is storing in database .
how to solve this problem . how to send dynamic value in input type file . any help ?
you may also use this
Fetch this $existing_category_image from database no need to post it from form.
if($imageData == '' || $imageData == null){
$sql = "UPDATE room SET cat_id='$cat_id', room_no='$room_number', room_desc='$room_desc' WHERE room_id='$current_id'";
}else{
$sql = "UPDATE room SET cat_id='$cat_id', room_no='$room_number', room_desc='$room_desc', room_image='$imageData' WHERE room_id='$current_id'";
}
OR
Write this:
if($imageData == '' || $imageData == null){
$imageData = $existing_category_image;
}
before
$sql = "UPDATE room SET cat_id='$cat_id', room_no='$room_number', room_desc='$room_desc', room_image='$imageData' WHERE room_id='$current_id'";
I need some js/ajax/jquery script saving data to database dynamically when I check the check-box.
the checkboxes at the moment or loaded in next to records and change the variable in the database depending if its checked or not.but i have to reload the page after i select one to save it to the database. i can do everything else but understand how to implement the ajax to this so i don't have to submit the query and refresh the page every time. any help is greatly appreciated.
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['first']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type=text name="comment" placeholder="Comments Box">
<input type=text name="cost" placeholder="Cost">
<input type="submit" value="Save" name="Save">
</form>
<?php
//Job Status
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE repairs SET status = '".(isset($activate)?'Completed':'In Progress')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Job Status
//Payment Status
if(isset($_POST['paycheck'])){$paycheck = $_POST['paycheck'];
if(isset($_POST['paid'])?$paid = $_POST["paid"]:$unpaid = $_POST["unpaid"])
$id = "('" . implode( "','", $paycheck ) . "');" ;
$sql="UPDATE repairs SET paid = '".(isset($paid)?'Paid':'Unpaid')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Payment Status
//Return Status
if(isset($_POST['retcheck'])){$retcheck = $_POST['retcheck'];
if(isset($_POST['ret'])?$ret = $_POST["ret"]:$unret = $_POST["unret"])
$id = "('" . implode( "','", $retcheck ) . "');" ;
$sql="UPDATE repairs SET ret = '".(isset($ret)?'Retuned':'In Office')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Return Status
$sql="SELECT * FROM $tbl_name";
if(isset($_POST['all'])){
$sql="SELECT * FROM $tbl_name";
}
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%'";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%'";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%'";
}
$result=mysql_query($sql);
?>
<form name="frmactive" method="post" action="">
<input name="activate" type="submit" id="activate" value="Complete Job" />
<input name="paid" type="submit" id="Payment" value="Payment Status" />
<input name="ret" type="submit" id="ret" value="Returned 2 Student" />
<br />
<a id="displayText" href="javascript:toggle();">Show Extra</a>
<div id="toggleText" style="display: none">
<br />
<input name="unret" type="submit" id="unret" value="In Office" />
<input name="unpaid" type="submit" id="unpaid" value="Not Paid" />
<input name="deactivate" type="submit" id="deactivate" value="In Progress" /></div>
<table width="1000" border="0" cellpadding="3" cellspacing="1">
<thead>
<th width="67" align="center"><strong>Start Date</strong></th>
<th width="50" align="center"><strong>Cases</strong></th>
<th width="34" align="center"><strong>Type</strong></th>
<th width="120" align="center"><strong>Damage</strong></th>
<th width="31" align="center"><strong>Comment</strong></th>
<th width="31" align="center"><strong>Cost</strong></th>
<th width="90" align="center"><strong>Payment Status</strong></th>
<th width="100" align="center"><strong>Returned 2 Student</strong></th>
<th width="100" align="center"><strong>Job Status</strong></th>
</thead>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['start']; ?></td>
<td><? echo $rows['cases']; ?></td>
<td><? echo $rows['type']; ?></td>
<td width="70"><? echo $rows['damage']; ?></td>
<td width="70"><? echo $rows['comment']; ?></td>
<td><? echo "$"; echo $rows['cost']; ?></td>
<!--Payment Display(Start)-->
<?php
if($rows['paid']=="Paid")
{
?>
<td><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid'];?>
</td>
<?
}
if($rows['paid']=="Unpaid")
{
?>
<td width="21"><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid']; ?>
</td>
<?
}
if($rows['ret']==""){
?>
<td width="50">No Data</td>
<?
}
?>
Do it with jQuery, a simple example could be:
HTML:
<input type="checkbox" name="option1" value="Milk">
<input type="checkbox" name="option2" value="Sugar">
<input type="checkbox" name="option3" value="Chocolate">
JS:
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('file.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
PHP: file.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('mydb');
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO table (value) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
Simple put...
$('input:checkbox').click( function() {
clicked = $(this).attr('checked');
if (clicked) {
/* AJAX the server to tell them it was clicked. */ }
else {
/* AJAX the server to tell them it was unclicked. */ } } );
I can make this even simpler. first, you need to ad a checkbox!!
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['frist']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange="fill_damage(document.form1aa.type.selectedIndex);">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type="text" name="comment" placeholder="Comments Box">
<input type="text" name="cost" placeholder="Cost">
<input type="checkbox" name="somecheck" onchange="if(this.checked)document.form1aa.submit()">Check this to Save.
<input type="submit" value="Save" name="Save">
</form>
<script type="javascript>
//another function that works for onchange="dosubmit(this)"
//IF you put it after the form.
function dosubmit(el) {
if (el.checked) {
document.form1aa.submit();
}
}
</script>
get rid of the spaces in your onchange events where possible.
If you have dynamic checkbox list and you want to dynamically save the clicked one to database or inserting the unchecked one, here how to do that:
Html/PHP
<?php
// $checklists are models that I am getting from db
$checklists = CheckList::getCheckLists(3);
echo '<ul>';
foreach ($checklists as $checklist) {
$isChecked = $checklist->getAnswer($requestID, $checklist->primaryKey);
$checked = $isChecked ? "checked" : "";
echo '<li>';
echo "<input id='{$checklist->primaryKey}'
name='{$checklist->primaryKey}' type='checkbox' {$checked}
value='{$isChecked}' data-request-id='{$requestID}'>
$checklist->check_list_text";
echo '</li>';
}
echo '</ul>';
?>
Jquery
<script>
$("input[type='checkbox']").on('click', function(){
var checkbox = $(this);
var checked = checkbox.prop('checked');
var checklistId = checkbox.attr("id");
$.ajax({
url:"<?= Url::to(['default/add-checklist-answer']) ?>",
// I don't need to write the type here because I am using Yii Framework
// type: 'post',
data: {
checklistId: checklistId,
requestId: checkbox.data('request-id'),
checked: checked
},
success: function(data) {
//alert(data);
console.log(data.firstMessage)
},
error: function(data) {
// alert(data);
}
});
});
</script>
I hope it will work for MVC users.