Delete selected row from table in php - php

I am using the code (pasted below) to delete the record from the table when it's selected by the checkbox. It is working, but it is not deleting the record from the table, it is only showing the echo "Records deleted Successfully.".
Please have a look at my code and suggest me some changes.
<?php
echo "Hiiiiiiiiii";
include("conn.php");
$sql="select * from test ";
$res=mysql_query($sql) or die(mysql_error());
?>
<form name="form1" method="POST" action="">
<table width="578" border="1" align="center" id="menu">
<tr>
<th></th>
<th>id</th>
<th>Name</th>
<th>email</th>
<th>phno</th>
</tr>
<?php
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['emailid'];?></td>
<td><?php echo $row['phno'];?></td>
<?php
echo"<td><a href='update.php?id=".$row['id']."'>Update</a></td>";
?>
<?php
}
?>
<tr><td><input type="submit" name="delete" value="Delete" id="delete"></td></tr></tr></table>
<?php
// Check if delete button active, start this
$count = mysql_num_rows($res);
echo "$count";
if(isset($_POST['delete']))
{
$delete_id = $_POST['checkbox'];
$id = count($delete_id );
if (count($id) > 0)
{
foreach ($delete_id as $id_d)
{
$sql = "DELETE FROM `test` WHERE id='$id_d'";
$delete = mysql_query($sql);
}
}
if($delete)
{
echo $id." Records deleted Successfully.";
}
}
>?

Add error_reporting(E_ALL); to the top of your file. Now you will be able to see all errors. http://php.net/manual/en/function.error-reporting.php
Also, use var_dump() to check what is actually in your variables. When you run var_dump($_POST); you can clearly see what is actually in your post.
http://php.net/manual/en/function.var-dump.php

if(isset($_POST['delete'])){
$delete = false;
$ids = array();
foreach($_POST['checkbox'] as $val){
$ids[] = (int) $val;
}
$ids = implode("','", $ids);
$sql = "DELETE FROM `test` WHERE id IN ('".$ids."')";
$delete = mysql_query($sql);
$id = mysql_affected_rows();
if($delete){
echo $id." Records deleted Successfully.";
}
}
also your check-boxes should have:
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $row['id']; ?>">

Put the delete code before selecting the records, then only you can see the actual records available in the DB.
<?php
echo "Hiiiiiiiiii";
include("conn.php");
if(isset($_POST['delete']))
{
$delete_id = $_POST['checkbox'];
$id = count($delete_id );
if (count($id) > 0)
{
foreach ($delete_id as $id_d)
{
$sql = "DELETE FROM `test` WHERE id='$id_d'";
$delete = mysql_query($sql);
}
}
if($delete)
{
echo $id." Records deleted Successfully.";
}
}
$sql="select * from test ";
$res=mysql_query($sql) or die(mysql_error());
?>
<form name="form1" method="POST" action="">
<table width="578" border="1" align="center" id="menu">
<tr>
<th></th>
<th>id</th>
<th>Name</th>
<th>email</th>
<th>phno</th>
</tr>
<?php
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['emailid'];?></td>
<td><?php echo $row['phno'];?></td>
<?php
echo"<td><a href='update.php?id=".$row['id']."'>Update</a></td>";
?>
<?php
}
?>
<tr><td><input type="submit" name="delete" value="Delete" id="delete"></td></tr></tr></table>
<?php
// Check if delete button active, start this
$count = mysql_num_rows($res);
echo "$count";
>?

<? echo $rows['id']; ?>
there is no $rows here remove the s put
<? echo $row['id']; ?>

You should name the checkboxes something like
name="checkbox[<?php echo $row['id'] ?>]"
And then when you're trying to delete
foreach ($_POST['checkbox'] as $id => $delete) {
// delete id
}
Your way of selecting an id by count is rather awkward, you're also only deleting 1 row, which is apparently non-existant because the count is not an id.
Also, the value of a checkbox is meant to be an indicator off the checkbox being ticked or not, it's not usually holding a value, the usual way is to make the name hold what the checkbox actually means.

There is a Typo in the code that outputs the id:
... value="<? echo $rows['id']; ?>">
It should be
... value="<? echo $row['id']; ?>">
Note that your code is also vulnerable to SQL-injection attacks. You should check if the ids in the POST-request are really integers.

you should move this code below of include("conn.php"); in your code
if (isset($_POST['delete'])) {
$delete_id = $_POST['checkbox'];
$id = count($delete_id);
if (count($id) > 0) {
foreach ($delete_id as $id_d) {
$sql = "DELETE FROM `test` WHERE id='$id_d'";
$delete = mysql_query($sql);
}
}
if ($delete) {
echo $id . " Records deleted Successfully.";
}
}

<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id'];?>"></td>
<td><?php echo $row['id'];?></td>
Need to change as below to work it perfectly:
<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="**<?php** echo $rows['id']; ?>"></td>

Related

update multiple rows in one sql query

Im new in php. this problem stuck me for two days. ergh. I want to display a table that contain input field so that user can insert the data and update it into database. User can change all the data in the table. I want to update multiple rows at a time, but it ends up updating only 1 row (the last row). Anyone please help me for this. Thnks.
This are the form.
This are the following code.
[<table>
<thead>
<tr>
<td><b>Item Code</b></td>
<td><b>Item Barcode</b></td>
<td><b>Item</b></td>
<td><b>QOH</b></td>
<td><b>Quantity</br>Checked</b></td>
<td><b>Quantity</br>Order</b></td>
</tr>
</thead>
<?php
$Barcode=$_SESSION\["Barcode"\];
$code=$_SESSION\["Code"\];
$itemcode=$_SESSION\["Itemcode"\];
$guid=$_SESSION\["guid"\];
$sql = "SELECT itemmastersupcode.*, itembarcode.*, stock_count_item.*, stock_count.*, po_ex_c.*, d.itemlink_total_qty
FROM itemmastersupcode
WHERE stock_count.SupCode = '$code' and stock_count_item.TRANS_GUID = '$guid'
GROUP BY itemmastersupcode.Itemcode";
$result=mysqli_query($conn2,$sql);
$rowcount = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result))
{
?>
<tbody>
<tr>
<td><?php echo $row\["Itemcode"\]; ?></td>
<td><?php echo $row\["Barcode"\]; ?></td>
<td><?php echo $row\["Description"\]; ?></td>
<td><?php echo $row\["itemlink_total_qty"\]; ?></td>
<td><?php echo $row\["qty"\]; ?></td>
<form class="form-inline" role="form" method="POST" id="myForm">
<td><input type="number" name="qty" value=""/></td>
</tr>
</tbody>
<input type="hidden" name="itemcode" value="<?php echo $row\["itemcode"\]; ?>"/>
<input type="hidden" name="supcode" value="<?php echo $_SESSION\["Code"\] ?>"/>
<input type="hidden" name="guid" value="<?php echo $_SESSION\["guid"\] ?>"/>
<?php
}
?>
</table>
<button name="save" type="submit" ><b>SUBMIT</b></button>
</form>
<?php
if (isset($_POST\["save"\]))
{
$itemcode=$_POST\['itemcode'\];
$qty=$_POST\['qty'\];
$supcode=$_POST\['supcode'\];
$guid=$_POST\['guid'\];
$sql = "UPDATE stock_count, stock_count_item SET stock_count.posted = '1', stock_count_item.qty_order = '$qty'
WHERE stock_count.TRANS_GUID = '$guid' AND stock_count_item.Itemcode ='$itemcode'
and stock_count_item.TRANS_GUID = '$guid' ";][1]
An UPDATE query will update all records that are filtered by the WHERE clause. If no WHERE is given, all records are updated:
UPDATE table1 SET field1='value1';
will set the field1 column of all records to value1.
UPDATE table1 SET field1='value1' WHERE field2='value2';
will set the field1 column to value1 or all records where field2 is equal to value2.
So, in your case, the records that are found through the WHERE clause are updated. This is all basic SQL stuff by the way, so I advise you to read up on SQL.
Finally, also use prepared statements in your code to prevent SQL injection.
<table>
<thead>
<tr>
<td><b>Item Code</b></td>
<td><b>Item Barcode</b></td>
<td><b>Item</b></td>
<td><b>QOH</b></td>
<td><b>Quantity</br>Checked</b></td>
<td><b>Quantity</br>Order</b></td>
</tr>
</thead>
<?php
$Barcode=$_SESSION["Barcode"];
$code=$_SESSION["Code"];
$itemcode=$_SESSION["Itemcode"];
$guid=$_SESSION["guid"];
$sql = "SELECT itemmastersupcode.*, itembarcode.*, stock_count_item.*, stock_count.*, po_ex_c.*, d.itemlink_total_qty
FROM itemmastersupcode
WHERE stock_count.SupCode = '$code' and stock_count_item.TRANS_GUID = '$guid'
GROUP BY itemmastersupcode.Itemcode";
$result=mysqli_query($conn2,$sql);
$rowcount = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result))
{
?>
<tbody>
<tr>
<td><?php echo $row["Itemcode"]; ?></td>
<td><?php echo $row["Barcode"]; ?></td>
<td><?php echo $row["Description"]; ?></td>
<td><?php echo $row["itemlink_total_qty"]; ?></td>
<td><?php echo $row["qty"]; ?></td>
<form class="form-inline" role="form" method="POST" id="myForm">
<td><input type="number" name="itemcode[<?php echo $row["itemcode"]; ?>][qty]" value=""/></td> //update here
</tr>
</tbody>
<?php
}
?>
</table>
<input type="hidden" name="supcode" value="<?php echo $_SESSION["Code"] ?>"/> //update here
<input type="hidden" name="guid" value="<?php echo $_SESSION["guid"] ?>"/>//update here
<button name="save" type="submit" ><b>SUBMIT</b></button>
</form>
Php content
<?php
if (isset($_POST["save"]))
{
$itemcodes=$_POST['itemcode'];
$qty=$_POST['qty'];
$supcode=$_POST['supcode'];
$guid=$_POST['guid'];
$sql = "UPDATE stock_count, stock_count_item SET
stock_count.posted = '1',
stock_count_item.qty_order = CASE stock_count_item.Itemcode";
foreach( $itemcodes as $itmcode=>$qty)
{
$sql.=" WHEN ".$itmcode." THEN ".$qty
}
$sql.=" END WHERE stock_count.TRANS_GUID =$guid AND stock_count_item.TRANS_GUID=$guid AND stock_count_item.Itemcode IN (".implode(",",array_keys( $itemcodes)).") ";
?>
Hope it will help

No error message in this code but it doesn't delete the fields

In this code I don't have any error messages but it doesn't delete the data. By the way the database has many records and the names of all the fields are correct.
<?php
if ($connect = mysqli_connect('localhost', 'root', 'adminpass', 'flip'))
{
$id = $_GET['id'];
$sql = "SELECT * FROM threads ORDER BY id DESC";
$query = mysqli_query($connect, $sql);
$num = mysqli_num_rows($query);
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" >
<table border="1" width="400" cellpadding="0" cellspacing="0">
<tr>
<td>#</td>
<td>id</td>
<td>subject</td>
</tr>
<?php
while ($row = mysqli_fetch_array($query))
{
?>
<tr>
<td> <input type="checkbox" name="checkbox[]" value="<?php echo $row['id'] ?>"></td>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['topic'] ?></td>
</tr>
<?php
}
?>
<input type="submit" name="delete" value="delete" >
<?php
if (isset($delete))
{
for ($i = 0; $i < $num; $i++)
{
$del_id = $checkbox[$i];
$sql2 = "DELETE FROM threads WHERE id='$del_id'";
$query2 = mysqli_query($connect, $sql2);
}
if ($query2)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete.php\">";
}
}
mysqli_close($connect);
?>
</table>
</form>
What is the problem with it?
You can try this:
<?php
/* ESTABLISH CONNECTION */
$connect=mysqli_connect("localhost","root","adminpass","flip");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if(isset($_POST['delete'])){ /* IF DELETE IS CLICKED */
$checkbox=$_POST['checkbox'];
$hiddencounter=mysqli_real_escape_string($connect,$_POST['hiddencounter']); /* PREVENT A BIT OF SQL INJECTION */
for($i=0;$i<$hiddencounter;$i++){ /* FOR LOOP BASED ON THE NUMROWS BELOW */
if(!empty($checkbox[$i])){ /* IF THE CHECKBOX IS TICKED */
$del_id=mysqli_real_escape_string($connect,$checkbox[$i]); /* PREVENT A BIT OF SQL INJECTION */
$sql2="DELETE FROM threads WHERE id='$del_id'";
$query2=mysqli_query($connect,$sql2); /* IMPLEMENT THE DELETE QUERY */
}
} /* END OF FOR LOOP */
echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete.php\">";
} /* END OF ISSET DELETE */
?>
<form action="" method="POST" > <?php /* YOU CAN LEAVE THE ACTION BLANK, TO SUBMIT THE FORM ON THE PAGE ITSELF */ ?>
<table border="1" width="400" cellpadding="0" cellspacing="0">
<tr>
<td>#</td>
<td>id</td>
<td>subject</td>
</tr>
<?
$sql="SELECT * FROM threads ORDER BY id DESC";
$query=mysqli_query($connect,$sql);
$num=mysqli_num_rows($query);
/* SUBMIT THE NUMBER OF ROWS QUERIED THROUGH HIDDEN INPUT */
echo "<input type='hidden' name='hiddencounter' value='$num'>";
while($row=mysqli_fetch_array($query)){ /* FETCH DATA */
?>
<tr>
<td><input type="checkbox" name="checkbox[]" value="<?php echo $row['id'] ?>"></td>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['topic'] ?></td>
</tr>
<?
} /* END OF WHILE LOOP $QUERY */
?>
<input type="submit" name="delete" value="delete" >
<?php
mysqli_close($connect);
?>
</table>
</form>
Explanation why your code did not work:
Your isset($delete): where does $delete variable came from?
Your for loop doesn't determine if the checkboxes submitted has values or not.
Your <meta> redirect. It redirects to delete.php after the for loop, so that is the reason you don't see any errors. But I'm pretty sure you would see some errors if you remove the <meta> redirect.
Even if the delete is working, you wouldn't see the result right after because the delete query is after your fetching of data.
You have an error in your Variable:
if (isset($delete))
Should be:
if (isset($_POST['$delete']))
I don't see where $delete variable is ever set in your code. At the moment $delete is not set, therefor if(isset($delete)) is false.
To me it would appear you are trying to use Registered Globals. Or you just forgot to set $delete to one of your $_GET[] or $_POST[] variables.
"Warning
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0."
PHP manual - Security Globals
Predefined Variables

Want to update multiple records using checkboxes and save button

I am searching some records using two text boxes and then updating the selected records in database. i am able to see the value row id of the selected checkbox but when i want to get the value for updation in database it gives 0, i.e showing no record in array
Here is my code
if($_POST["search"])
{
$nitnumber = $_POST["nitnumber"];
$workno = $_POST["workno"];
$query = "select * from print where nit = $nitnumber and work = $work";
$result = mysql_query($query) or die ("<font color =red>NIT Number and/or Work Number is Missing</font>");
$count = mysql_num_rows($result);
if($count == 0)
echo "<font color=red>Record not found</font>";
else
{
while($record = mysql_fetch_assoc($result))
{
?>
<tr class="odd">
<td><div align="center"><?php echo $record['a']; ?></div></td>
<td><div align="center"><?php echo $record['b']; ?></div></td>
<td><div align="left"><?php echo $record['c']; ?></div></td>
<td> <div align="left">
<?php
enter code hereecho $record["d"];
?>
</td>
<td>
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>">
<?php echo $record["id"];?>
</td>
<?php } } }?>
<tr>
<td colspan="5" align="right"> <input type="submit" value="Save" name="save"> </td>
</tr>
<?php
if ($_POST['save'])
{
$num_chkboxes=count($_POST['checkbox']);
for($i=0; $i<$num_chkboxes; $i++){
$complete = intval($checkbox[$i]);
echo $complete;
var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
//$Result1 = mysql_query($updateSQL, $FamilyOrganizer) or die(mysql_error());
}
}
?>
<?php
if ($_POST['save'])
{
$checkbox1 = $_POST['chk1'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1)
{
$selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);
$updateSQL = "" // your update query here
}
?>
<input type="checkbox" name="chk1[]" value=""> // take checkboxes like this
First, the problem started when you fill the values of the checkboxes:
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>" />
you must gave them the value like
value="<?php echo $record['id'] ?>"
Second, you don't get the values of the checkboxes as you should:
for($i = 0; $i < count($_POST['checkbox']); $i++){
$complete = intval($_POST['checkbox'][$i]);
//echo $complete;
//var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
}
Another thing you should take care about is the assigning of the elements ids:
id="checkbox[]"
you must give unique ids for each element:
id="checkbox-1"
id="checkbox-2"

how to get the value of multiple checkbox in php

I have use the following code to select multiple value for selected checkbox to delete it from database table but when I am print_r its only shows keys for it not showing value for id.
I have use this code to get value in array:-
<?php
echo "Hiiiiiiiiii";
include("conn.php");
$sql="select * from test ";
$res=mysql_query($sql) or die(mysql_error());
?>
<form name="form1" method="POST" action="">
<table width="578" border="1" align="center" id="menu">
<tr>
<th></th>
<th>id</th>
<th>Name</th>
<th>email</th>
<th>phno</th>
</tr>
<?php
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['emailid'];?></td>
<td><?php echo $row['phno'];?></td>
<?php
echo"<td><a href='update.php?id=".$row['id']."'>Update</a></td>";
?>
<?php
}
?>
<tr><td><input type="submit" name="delete" value="Delete" id="delete"></td></tr></tr></table>
<?php
// Check if delete button active, start this
$count = mysql_num_rows($res);
echo "$count";
if(isset($_POST['delete']))
{
if(count($_POST['checkbox']) !=0)
{
$array = array("checkbox" => $_POST['checkbox']);
print_r($array);
$ids = implode(',', $array);
echo "$ids";
$result = mysql_query("DELETE FROM test WHERE id IN ($ids)") or die(mysql_error());
}
}
// if successful redirect to delete_multiple.php
if($result)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=teach_delinquent.php\">";
echo "SUCCESS";
}
?>
$_POST['checkbox'] array will contain only checked boxes:
$ids = array();
foreach($_POST['checkbox'] as $val){
$ids[] = (int) $val;
}
$ids = implode(',', $ids);
I've done the foreach to make all id's INT for security purposes.
Quick fix of your question is as follows
Replace below line
$array = array("checkbox" => $_POST['checkbox']);
with
$array = $_POST['checkbox'];
or
$array = array_map('intval',$_POST['checkbox']); // if all values are integer ---for security
because $_POST['checkbox'] is already an array
Hope this will fix your problem
First of all you need to count how many checkboxes are there
$counter = sizeof($_POST['checkbox']);
The run a loop to access all of these values
for($i=0;$i<=$counter;$i++){
$checkbox_val = $_POST['checkbox'][$i];
}
That's all you need

Delete multiple rows mysql with checkbox

please help in deleting multiple rows from a table.
home.php
<form action="del.php" method="get" enctype="multipart/form-data">
<?php
while($row=mysql_fetch_array($rs))
{
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<?php echo $row['id']; ?>]" type="checkbox" id="checkbox[<?php echo $row['id']; ?>]" value="<?php echo $row['id']; ?>"></td>
<td><?php echo $row['listingtype'];?></td>
<td><?php echo $row['propertyname'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['listdate'];?></td>
</tr>
<?php
}
?>
</table>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr></form>
del.php
<?php
include "include/db.php";
$tbl_name='propertylistingbasicinfo';
// Check if delete button active, start this
if ( ! empty($_POST['delete'])) {
foreach ($_POST['need_delete'] as $id => $value) {
$sql = 'DELETE FROM `'.$tbl_name.'` WHERE `id`='.(int)$id;
mysql_query($sql);
}
header('Location: home.php');
}
?>
Error : When i click on delete button, blank screen come.
And url looks like this : http://localhost/realestate/del.php?need_delete%5B2%5D=2&delete=Delete
your mixing up GET with POST, change form method to post
You need something similar to this in your form
<input type="checkbox" name="record[]" value="<?php echo $id ?>">
then you can use implode() function to concatenate ids and remove them
$deleted = implode(',',$_POST['record']);
$query = mysql_query("delete from table where id in ('$deleted') ");
Not tested but this the idea.
The problem is that you are submitting the form with method="get" and in del.php, you are accessing values from $_POST. Change method="get" to method="post" on home.php
I would change it to the following...
home.php:
<form action="del.php" method="post" enctype="multipart/form-data">
<table>
<?php while($row=mysql_fetch_array($rs)) { ?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="need_delete[]" value="<?php echo $row['id']; ?>" type="checkbox" id="checkbox[<?php echo $row['id']; ?>]" />
</td>
<td><?php echo $row['listingtype'];?></td>
<td><?php echo $row['propertyname'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['listdate'];?></td>
</tr>
<?php } ?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete" />
</td>
</tr>
</table>
del.php:
<?php
//Get the db-file and set the table name
include "include/db.php";
$tbl_name='propertylistingbasicinfo';
// Check if delete button active, start this
if ( !empty($_POST['delete'])) {
//Let's sanitize it
$sanitized_post_ids = array();
foreach($_POST['need_delete'] as $id ) $sanitized_post_ids[] = intval($id);
//Get the ids and add a trailing ",", but remove the last one
$in_str = substr(implode(',', $sanitized_post_ids), 0, -1);
//Build the sql and execute it
$sql = 'DELETE FROM ' . $tbl_name ' WHERE id IN (' . $in_str . ')';
mysql_query($sql);
//Redirect!
header('Location: home.php');
}
?>
Hope this works out for you (and that I didn't manage to add a typo or similar misshaps)!

Categories