Cannot delete row using check box - php

I'm trying to delete a row from table which is connected to database using checkbox (and it wouldn't matter if its just one row or multiple rows), but it is not working, as in nothing happens. It doesn't delete, no errors or warnings appear just a refresh.
php:
<?php
if(isset($_POST['del_event']))
{
if(isset($_POST['check']) && count($_POST['check']))
{
$array = array("check" => $_POST['check']);
$id = implode(',', $array['check']);
$result = mysql_query("DELETE FROM event WHERE event_id = '$id'") or die(mysql_error());
}
}
?>
html:
<form class="buttons" method="post" action="event.php">
<div class="button-wrap">
<input type="button" id="add_event" name="add_event" value="Add Event"/>
<input type="submit" id="del_event" name="del_event" value="Delete Event"/>
</div>
</form>
<tbody class="tbody-event-list-table2">
<?php
require "connection.php";
$check = mysql_query("SELECT * FROM event") or die(mysql_error());
if(mysql_num_rows($check) > 0)
{
while($row = mysql_fetch_array($check))
{
$id = $row['event_id'];
$name = $row['event_name'];
$start = $row['start'];
$end = $row['end'];
$venue = $row['event_venue'];
echo
"<tr>
<td><input type='checkbox' name='check' id='check' class='check' value='$id'/><a href=''
class='event-link'>$name</a></td><td>$start</td><td>$end</td><td>$venue</td>";
echo "</tr>";
}
}
else
{
echo
"<tr>
<td colspan='4'>There Are No Events.</td>
</tr>";
}
?>
</tbody>
It is if(isset($_POST['del_event'])) because 'del_event' is a name of a delete button which is disabled unless a checkbox is checked.
<script>
var chkbox = $(".check"),
button = $("#del_event");
button.attr("disabled","disabled");
chkbox.change(function(){
if(this.checked){
button.removeAttr("disabled");
}else{
button.attr("disabled","disabled");
}
});
</script>
php version is 5.5.9

This would still give you an undefined error if it is the check variable
if (isset($_POST['check']) && count($_POST['check']) != 0)
but if a checkbox is off in a form it is not sent with the form so it does not exist.
Carpetsmoker was halfway right, a proper solution would be:
if (isset($_POST['check'])) {
if ( (int) $_POST['check'] !== 0) {
}
}
btw, it is better to always cast your variables to a propert type you are checking for.
In PHP 0 can be 0, false or null.
Prevent this by safe type checking with the ===

so i fixed the prob. first i had to remove "form" that was separating the buttons and the table so now "form" is wrapped around both buttons and table. second is the php coding for deletion has changed too.
<form class="buttons" method="post" action="event.php">
<div class="button-wrap">
<input type="button" id="add_event" name="add_event" value="Add Event"/>
<input type="submit" id="del_event" name="del_event" value="Delete Event"/>
<input type="submit" id="edit_event" name="edit_event" value="Edit Event">
</div>
<div class="event-list-table2" >
<table class="event-table">
<thead>
<tr>
<th>Event Name</th>
<th>Start Event</th>
<th>End Event</th>
<th>Venue</th>
</tr>
</thead>
<tbody class="tbody-event-list-table2">
<?php
require "connection.php";
$check = mysql_query("SELECT * FROM event") or die(mysql_error());
if(mysql_num_rows($check) > 0)
{
while($row = mysql_fetch_array($check))
{
$id = $row['event_id'];
$name = $row['event_name'];
$start = $row['start'];
$end = $row['end'];
$venue = $row['event_venue'];
echo
"<tr>
<td><input type='checkbox' name='check[]' class='check' value='$id'><a href='' class='event-link' value='$id' name='event-link'>$name</a></td><td>$start</td><td>$end</td><td>$venue</td>";
echo "</tr>";
}
}
else
{
echo
"<tr>
<td colspan='4'>There Are No Events.</td>
</tr>";
}
?>
</tbody>
<?php
if (isset($_POST['del_event']) && isset($_POST['check']))
{
foreach($_POST['check'] as $del_id)
{
$del_id = (int)$del_id;
$sql = mysql_query("DELETE FROM event WHERE event_id = $del_id") or die(mysql_error());
if($sql)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=event.php\">";
}
}
}
?>
</table>
</div>
</form>

Related

How can i update html table row which display sql data when click button in each row?

When i click Issue button allows to click first row button. second row button not working.
So i want to update the table rows i want.
Here is the interface - first row only update when click 2nd row not allows to click issue button.
Interface Table
Here itemdisplay.php page with ajax script.
<?php
include('../db_connector.php');
$req = $_GET['cat1'];
$query = "select i.item_name ,r.qty, i.item_id , r.reqID, r.av from items i
JOIN req_items r on r.item_name = i.item_id
JOIN req rq on r.req_number = rq.req_number
WHERE i.status = 'common' AND
rq.req_number = $req and r.status = 'approved'
GROUP BY i.item_name ";
$result = mysqli_query($con,$query);
?>
<table class="table table-hover" >
<thead>
<tr>
<th>#</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Stock Available </th>
</tr>
</thead>
<tbody>
<?php
#$count = mysqli_num_rows($result);
$itemCount = 1;
if($count > 0) {
while ($row = mysqli_fetch_array($result)) {
$name = $row['item_name'];
$qty = $row['qty'];
$id = $row['item_id'];
$rqId = $row['reqID'];
$av = $row['av'];
$query1 = "select m.stock_level
from main_stock m
where m.item_id = $id and m.depot_id = 27";
$result1 = mysqli_query($con, $query1);
#$count = mysqli_num_rows($result1);
if ($count > 0) {
while ($row = mysqli_fetch_array($result1)) {
$level = $row['stock_level'];
?>
<tr id="mydiv">
<td><?php echo $itemCount; ?></td>
<td hidden><input class="form-control" name="rqId"
type="text" id="rqId" readonly value="<?php echo $rqId; ?>"></td>
<td><input class="form-control" name="name" type="text"
id="name" readonly value="<?php echo $name; ?>"></td>
<td><input class="form-control" name="qty" type="text"
id="qty" readonly value="<?php echo $qty; ?>"></td>
<td><input class="form-control" name="level" type="text"
id="level" readonly value="<?php echo $level; ?>"></td>
<td hidden><?php echo $av; ?></td>
<?php
if($level < $qty) {
if ($av != 1) {
echo 'Do not exists the available stock !!';
?>
<td><button class="btn btn-primary" type="submit"
id="request" name="request">Request</button></td>
<?php
} else
{
?>
<td><p>Processing</p></td>
<?php
}
?>
<?php
} else
{
?>
<td><button class="btn btn-primary" type="submit"
id="issue" name="issue">Issue</button></td>
<?php
}
?>
</tr>
<?php
$itemCount++;
}
}
}
}
else{
echo 'No records found';
}
?>
</tbody>
</table>
<script>
$('#issue').click(function(){
$.ajax({
url:"./ajax/cIssue.php",
method:"POST",
data:$('#rqId').serialize(),
success:function(data)
{
$("#mydiv").load(location.href + " #mydiv");
}
});
});
</script>
Here is the cIssue.php Query file
<?php
include('../db_connector.php');
$id = $_POST["rqId"];
$query = "";
$query = "UPDATE `req_items`
SET `status` = 'issue'
WHERE `reqID`=$id";
$result = mysqli_query($con, $query);
echo "Item Issued !";
$r = "UPDATE `main_stock`
SET `stock_level` = `stock_level` - (select `qty`
from `req_items`
where `reqID`= $id )
WHERE `depot_id`='27' and `item_id`= (select `item_name`
from `req_items`
where `reqID`= $id ) ";
$l = mysqli_query($con, $r);
?>
i want to update any row i want when i click issue button. If you want more details about my code, i can provide.
Hi you are using id of element to click that is why it is recognising only the first Issue button .Please use a class instead for click event of Issue button.
$(".myIssuebtn").on("click",function(){
//your ajax call here.
});
<button class="btn btn-primary" class="myIssuebtn" type="submit"
id="issue" name="issue">Issue</button>

Updating all rows at once in codeigniter, error in query

I am trying to update multiple rows simultaneously and I think my query is somewhat messed up while i am trying to update all my rows simultaneously. I am using CodeIgniter framework. I want to work on my query and the data being sent from the view but unable to get a logic to update all rows simultaneously. Please note that there should be only one update button as this is a requirement
My View code is:
<form action="" method="post">
<table border="1" style="background:none;width:100%;" RULES="ROWS" class="tab_data">
<thead>
<th width="30px">No</th>
<th >Action Item</th>
<th>Responsibility</th>
<th>Order</th>
<th>Mandatory?</th>
<th width = "100px" align="center">Actions</th>
</thead>
<tbody>
<?php
$serial_no = 1;
if(count($rows))
{
foreach($rows as $row)
{
?>
<tr>
<td><?php echo $serial_no; ?></td>
<td>
<?php
echo "<input type='hidden' class='col-md-4 form-control' name='checklist_id' value='"
.$row['checklist_id']."' />";
echo $row['action_item'];
?>
</td>
<td>
<?php echo $row['responsibility']; ?>
</td>
<td>
<input type="hidden" name="row_id[]" value="<?php echo $row['sequence']; ?>">
<input type="text" class="form-control" name="order[]" value="<?php echo $row['sequence']; ?>">
</td>
<td>
<input type="checkbox" class="" name="if_checklist<?php echo $row->checklist_id; ?>" value="1" echo 'checked'; >
</td>
<td align="center">
<?php
echo anchor('exits/delete_absconding_checklist/'.$row['checklist_id'],
"<i class='fa fa-trash-o' alt='Delete' title='Delete' rel='".$row['id']."' ></i>",
array('rel' => $row->id, 'class' => 'edit_row'));
?>
</td>
</tr>
<?php
$serial_no++;
}
}
?>
<tr>
<td></td><td></td><td></td><td></td>
<td>
<input type="hidden" name="action" value="update_order">
<button type="submit" name="submit" class="btn btn-info pull-right">Update</button>
</td>
</tr>
</tbody>
</table>
</form>
My Controller Code is:
function display_absconding_checklist()
{
if($this->input->post('action') == '_doDelete' || $this->input->post('action') == '_doChangeStatus')
{
$this->admin_init_elements->delete_rows('applicant_status');
}
if($this->input->post('action') == 'update_order')
{
$this->exit_common->update_absconding_checklist();
}
$data['rows'] = $this->exit_common->get_all_absconding_checklists();
$this->data['maincontent'] = $this->load->view('maincontents/backend_display_absconding_checklist', $data, true);
$this->load->view('layout', $this->data);
}
My Model code is:
function update_absconding_checklist($post_array)
{
$post_array = $this->input->post();
foreach($post_array['checklist_id'] as $key => $rowid)
{
if($rowid > 0)
{
if(isset($post_array['if_checklist'.$rowid]))
$in = '1';
else
$in = '0';
$sql1 = "UPDATE pr_absconding_checklists SET `action_item` = '"
.$post_array['action_item'][$key]
."', `sequence` = '".$post_array['sequence'][$key]
."', `if_checklist` = '".$in
."' WHERE `checklist_id` = ".$rowid;
}
else
{
$sql1 = "UPDATE pr_absconding_checklists SET `action_item` = '"
.$post_array['action_item'][$key]
."', `sequence` = '".$post_array['sequence'][$key]
."', `if_checklist` = '".$in."'";
}
$query1 = $this->db->query($sql1);
}
}
I am getting no errors but there are many errors in my code and i am messed up, i am attaching my table snapshot also, please recommend improvements
My Table name is pr_absconding_checklists

update the database without page refresh

Whenever the hyperlink with the yes id is clicked i dont want the page to refresh and then show the status, i want the status to change instant without page refreshing. I know Ajax deals with this, but can anyone provide me with a working example with my code please? As it melting my head :/
<h3 class="page-header"> Enquiries </h3>
<form id="enquiry" method="post" action="enquiry_csv.php">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th> First Name</th>
<th> Last Name</th>
<th>Email</th>
<th>Message</th>
<th>Date</th>
<th>Responded to Enquiry?</th>
<th>Status</th>
<th></th>
<th><input class='btn-success' name='export' id='btnExport' type='submit' value='Export to CSV'/></th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM enquiries";
$select_enquiries = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($select_enquiries)) {
$Enquiry_ID = $row['Enquiry_ID'];
$FirstName = $row['First_Name'];
$LastName =$row['Last_Name'];
$Email = $row['Email'];
$Message = $row['Message'];
$Date =$row['Date'];
$Responded =$row['Responded'];
echo "<tr>";
echo "<td>$FirstName </td>";
echo "<td>$LastName </td>";
echo "<td>$Email </td>";
echo "<td>$Message </td>";
echo "<td>$Date </td>";
echo "<td> <a id='yes' class='success' style='' href='enquiries.php?Yes=$Enquiry_ID'>Yes</a> | <a class='success' href='enquiries.php?No=$Enquiry_ID'>No</a> </td>";
echo "<td> $Responded</td>";
echo "<td> <a class='btn btn-danger' href ='enquiries.php?delete=$Enquiry_ID'>Delete</a> </td>";
echo "</tr>";
}
?>
<?php
if(isset($_GET['Yes'])){
$enquiry_id = $_GET['Yes'];
$query = "UPDATE enquiries SET Responded = 'Yes' WHERE Enquiry_ID = {$Enquiry_ID}";
$query = mysqli_query($connection, $query);
}
if(isset($_GET['No'])){
$enquiry_id = $_GET['No'];
$query = "UPDATE enquiries SET Responded = 'No' WHERE Enquiry_ID = {$Enquiry_ID}";
$query = mysqli_query($connection, $query);
}
if(isset($_GET['delete'])){
$review_id = $_GET['delete'];
$query = "DELETE FROM enquiries WHERE Enquiry_ID = {$Enquiry_ID} ";
$delete_query = mysqli_query($connection, $query);
}
?>
<tr>
<td></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</form>
You can do it with jquery ajax api it performs an asynchronous HTTP (Ajax) request
http://api.jquery.com/jquery.ajax/
Refer the above link which #Sanya Zahid posted and try to do some thing like this:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var age = $("#age").val();
var dataString = 'name='+ name +'&age='+ age;
if(name=='' || age =='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" /><br>
<input id="age" name="age" type="text"/>
<div>
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Data</span>
<span class="success" style="display:none"> Data Saved!!</span>
</div>
</form>
Here submit.php contains database related stuff(insert/update/delete). I just added name and age fileds here in code. Add fields as per your form.
submit.php :
<?php
$conn = mysqli_connect("localhost","root","","test");
/* Insert form data with out page refresh */
if($_POST)
{
$name=$_POST['name'];
$age = $_POST['age'];
mysqli_query($conn,"Query will come here");
}else{
echo "Please try again!!";
}
/* Insert form data with out page refresh */
?>

Deleting selected item

Good day. I want to delete selected item by the user. But it turns out what ever button clicked by user, the first data row is deleting. Im stuck here. Please help.
This is my code:
HTML
<form method="POST" action="<?php $_PHP_SELF ?>">
<?php
$query = "select * from tblsr";
$request = mysql_query($query)or die(mysql_error());?>
<table class="table table-hover">
<tr>
<th>Softwares</th>
<th>Difficulty</th>
<th></th>
<th></th>
</tr>
<?php while($row = mysql_fetch_array($request)){
?>
<tbody>
<tr class="success">
<td><?php echo $row['Software']; ?></td>
<td><?php echo $row['Difficulty']; ?></td>
<td><input type="submit" class="btn btn-sm btn-success" name="change" value="Change Difficulty"/></td>
<td><input type="submit" class="btn btn-sm btn-danger" name="remove" value="Delete"/></td>
<input type="hidden" name="id[]" value="<?php echo $row['id']; ?>"/>
</tr>
</tbody>
<?php
}
?> </form>
DELETE Query
if(isset($_POST['remove'])){
$count = count($_POST['id']); //get total number of array element
for ($i = 0; $i < $count; $i++) {
$id = $_POST['id'][$i];
$sql = "Delete FROM tblsr
Where id = '$id'";
$success = mysql_query($sql) or die (mysql_error());
mysql_close();
if ($success == TRUE){
?>
<script>
alert('Deleted.');
window.location.href='manageRequest.php';
</script>
<?php
}
}
}
Your code's problem is that you never increase $i ( $i++ ) , and always your delete query affect on the first row ( id ) . you can put $i++ in your while loop to fix it, but I recommend that you simply do like below and don't bother yourself with a loop.
Delete query :
$rm = $_POST['id'];
if (isset($_POST['remove'])) {
foreach ($rm as $key => $value) {
$rm[$key] = "'".$value."'";
}
$sql = "Delete FROM tblsr
Where id IN(" . implode(",", $rm) .")";
die($sql);
$success = mysql_query($sql) or die(mysql_error());
if ($success) {
?>
<script>
alert('Deleted.');
window.location.href = 'manageRequest.php';
</script>
<?php
}
}
your form example for delete users:
<form method="POST" action="<?php $_PHP_SELF ?>">
<?php
$query = "select * from tblsr";
$request = mysql_query($query) or die(mysql_error());
?>
<table class="table table-hover">
<tr>
<th>Softwares</th>
<th>Difficulty</th>
<th></th>
<th></th>
</tr>
<?php
while ($row = mysql_fetch_array($request)) {
?>
<tbody>
<tr class="success">
<td><?php echo $row['Software']; ?></td>
<td><?php echo $row['Difficulty']; ?></td>
<td>
<input type="checkbox" name="id[]" value="<?php echo $row['id']; ?>"/>
delete
</td>
</tr>
</tbody>
<?php
}
?>
</table>
<button type="submit" name="remove" class="btn btn-success">
delete checked user
</button>
</form>

Records not getting inserted in ascending order

I'm having a strange problem. I have a HTML page with PHP code which inserts data to a MySQL database. The data gets saved to the DB without any errors but in an incorrect order.
Here's a screenshot. The table on the right side displays the existing records. The first 2 records are shown correctly.
But when I save more records, it displays like this.
Even in the MySQL table, the records are inserted that way.
I'm not sure where exactly the problem is so I've shown the whole code for the page below. I've commented what each code block does. Please comment if you need me to clarify something.
The Location ID is an auto-generated code.
<html>
<head>
<script language="javascript">
function SelectAll(source)
{ //The code for the 'Select All' checkbox
checkboxes = document.getElementsByTagName("input");
for(var i in checkboxes)
{
if(checkboxes[i].type == 'checkbox')
{
checkboxes[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<?php
//Database connection initialization
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new Location ID */
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID'];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
//$id_num = sprintf("%03d", $id_num);
$new_id = $id_letter . $id_num;
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<! The table which displays the existing records >
<div id="display">
<b>Locations</b><br/><br/>
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" >
<table border="1">
<tr>
<th>Location ID</th>
<th>Code</th>
<th>Location</th>
<th><i>Delete</i></th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><? echo $row["LID"]; ?></td>
<td align="center"><? echo $row["Code"]; ?></td>
<td><? echo $row["Location"]; ?></td>
<td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td>
</tr>
<?php
}
?>
</table>
<br/>
<div id="buttons2">
<input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" />
</div>
</form>
</div>
<! New record saving area >
<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
<form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Location ID</td>
<td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" name="code" style="text-align:right" /></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="loc" style="text-align:right" /></td>
</tr>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</div>
</form>
<?php
//Saving record
if(isset($_POST["savebtn"]))
{
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];
$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";
$result = mysql_query($query, $conn);
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<br/><br/>";
echo "<strong>1 record added successfully!</strong>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}
mysql_close($conn);
}
//Deleting selected records
if(isset($_POST["deletebtn"]))
{
for($i = 0; $i < $count; $i++)
{
$del_id = $_POST["checkbox"][$i];
$query = "DELETE FROM locations WHERE LID = '$del_id' ";
$result = mysql_query($query, $conn);
}
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">";
}
mysql_close($conn);
}
?>
</body>
</html>
Can anyone please tell me what is causing this and how to rectify it.
Thank you.
The records in the database are stored in the database in no particular order (well, there's some order to it, but it's up to the engine to determine it). If you want to get the results in a particular order, then you need to explicitly specify it when querying the data. In your case, make this change:
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations ORDER BY lid";
$result = mysql_query($query, $conn);

Categories