I'm attempting to delete a row from a table with data that is generated from a MySQL table. I took a look at both of these questions:
1. How to delete rows of database results using checkbox
2.Deleting multiple rows using checkboxes, PHP and MySQL.
I need help for code delete using checkboxes..
<?php
$sql = mysqli_query($conn, "SELECT * FROM leads ORDER BY lid ASC");
if(mysqli_num_rows($sql) == 0){
echo '<tr><td colspan="8">No Data Entry</td></tr>';
}else{
while($row = mysqli_fetch_assoc($sql)){
echo '<tr>
<td> <input name"checkbox[]" value"'.$row['lid'].'" type="checkbox"></td>
<td>'.$row['name'].'</td>
<td>'.$row['sex'].'</td>
<td>'.$row['phone'].'</td>
<td>'.$row['company'].'</td>
<td>'.$row['vehicle'].'</td>
</tr>';
}
}?>
Cancel
<?php
$del_lid = $_POST['checkbox'];
if (isset($_POST['submit'])) {
foreach($del_lid as $value){
$sql = "DELETE FROM leads WHERE lid='".$value."'";
$result = mysqli_query($conn, $sql);
}
}
?>
The checkboxes were missing the equals sign so effectively none of them had a value. The sql could be streamlined to use the in operator rather than a loop.
<table>
<?php
$sql = mysqli_query($conn, "SELECT * FROM leads ORDER BY lid ASC");
if( mysqli_num_rows($sql) == 0 ){
echo '<tr><td colspan="8">No Data Entry</td></tr>';
}else{
while($row = mysqli_fetch_assoc($sql)){
echo '
<tr>
<td> <input name="checkbox[]" value="'.$row['lid'].'" type="checkbox"></td>
<td>'.$row['name'].'</td>
<td>'.$row['sex'].'</td>
<td>'.$row['phone'].'</td>
<td>'.$row['company'].'</td>
<td>'.$row['vehicle'].'</td>
</tr>';
}
}
?>
</table>
<input type="submit" name="delete" class="btn btn-sm btn-primary" value="delete">
Cancel</td>
</form>
</div>
<?php
$del_lid = $_POST['checkbox'];
if ( isset($_POST['submit'] ) ) {
$sql='delete from `leads` where `lid` in ( ' . implode( ',', $del_lid ). ' )';
$result = mysqli_query($conn, $sql);
}
?>
Related
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>
i am fetching values from database & displaying in table with below code.
<tr>
<th>ORDERID</th>
<th>STATUS</th>
</tr>
<tr>
<td><?php echo $orderrecords[$k]["order_id"]; ?></td>
<td><?php echo $orderrecords[$k]["in_transit"]; ?></td>
</tr>
Requirement
values of drop down box are fetched from database in table header. when a user selects one of the option [ example : Undelivered ] in the drop down menu, then i need to display only the rows which have that value [ example : Undelivered ]
Issue :
I tried below code , now When user selects "Undelivered", its not filtering the Rows which have value "Undelivered", Instead its displaying all the rows in table and display value as "Undelivered" for all rows of table below Column.
<table>
<tr>
<th>ORDERID</th>
<th>
<select id="my_select" onchange="send_option();">
<option>Select an option</option>
<?php
$query = "SELECT DISTINCT in_transit FROM do_order";
$result = mysqli_query ($mysqli, $query);
while ( $row = mysqli_fetch_array($result) )
echo "<option value='" . $row['in_transit'] . "'>" . $row['in_transit'] . "</option>";
?>
</th>
</tr>
<?php
if(!empty($orderrecords))
{
foreach($orderrecords as $k=>$v)
{
?>
<tr>
<td><?php echo $orderrecords[$k]["order_id"]; ?></td>
<td>
<?php
if (isset($_POST['my_option']))
{
$query = "SELECT DISTINCT in_transit FROM do_order where in_transit like '" . $_POST["my_option"] . "'";
}
$result = mysqli_query ($mysqli, $query);
while( $row = mysqli_fetch_array($result) )
echo $row['in_transit']."<br>";
?>
</td>
</tr>
<?php
$tabindex++;
}
}
?>
</table>
<form method="post" action"dashboard.php" style="display:none" id="my_form">
<input type="text" id="my_option" name="my_option"/>
</form>
<form method="post" action"dashboard.php" style="display:none" id="my_form">
<input type="text" id="my_option" name="my_option"/>
</form>
script
function send_option () {
var sel = document.getElementById( "my_select" );
var txt = document.getElementById( "my_option" );
txt.value = sel.options[ sel.selectedIndex ].value;
var frm = document.getElementById( "my_form" );
frm.submit();
}
Of course!
When you submit the form, your script will get the list of all the order_id, loop it, append the current element to the first <td> of the table row, then it tests if you've submitted a specific in_transit. Which will always be correct, so it'll run the filtering query :
SELECT DISTINCT in_transit FROM do_order where in_transit like '" . $_POST["my_option"] . "'"
And whatever is the order_id, the second <td> will always be the selected $_POST["my_option"].
You are trying to filter the output, so you'll need to pass the selected my_option to the query that get the data.
So, to fix this, you need to rerun the outer query :
<?php
if (isset($_POST['my_option']))
{
$theBigQuery = "SELECT order_id, in_transit FROM do_order where in_transit like '" . $_POST["my_option"] . "'";
} else {
$theBigQuery = "SELECT order_id, in_transit FROM do_order";
}
$result = mysqli_query ($mysqli, $theBigQuery);
$orderrecords = mysqli_fetch_array($result, MYSQLI_BOTH);
if(!empty($orderrecords))
{
foreach($orderrecords as $k=>$v)
{
?>
<tr>
<td><?php echo $orderrecords[$k]["order_id"]; ?></td>
<td><?php echo $orderrecords[$k]["in_transit"]; ?></td>
</tr>
<?php
$tabindex++;
}
}
?>
I'm trying to work on an inventory system where users may view their inventory and update quantity with the value that input by user only and rest remains the same from database. But its not working please help me find where I did wrong. It will echo the success message but the database isn't updated.
<form name="form" method="post">
<table width="70%" border="5" align="center"><tr>
<th scope="row">SKU</th>
<th scope="row">Item Description</th>
<th scope="row">Current Qunatity</th>
<th scope="row">Update Quantity</th>
<th scope="row">Unit Price</th>
</tr>
<tr>
<th scope="row">
<?php
include('connect.php');
$result = mysqli_query("SELECT * FROM products")
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )) {
echo "<tr>";
echo '<td><a name="sku[]">'.$row['sku_id'].'</a></td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.$row['quantity'].'</td>';
echo '<td><input name="qty[]" /></td>';
echo '<td>'.$row['unit_price'].'</td>';
echo "</tr>";
}
?>
</table>
<input style="float:right" name="update" type="submit" id="update" value="Update"/>
</form>
<?php
if(isset($_POST['update']))
{
$qty = $_POST['qty'];
$sku = $_POST['sku'];
foreach($qty as $key => $value)
{
if(empty($value))
{
continue;
}
else
{
$sql = "UPDATE products SET quantity ='".$value."' WHERE sku_id = '".$sku[$key]."'";
mysql_query($sql);
}
}
$retval = mysqli_query($sql);
if(! $retval)
{
die('Could not update data: '. mysql_error());
}
echo 'Update data successfully!';
}
?>
You are using mysql_query here:
$sql = "UPDATE products SET quantity ='".$value."' WHERE sku_id = '".$sku[$key]."'";
mysql_query($sql);
Instead of mysqli_query:
$sql = "UPDATE products SET quantity ='".$value."' WHERE sku_id = '".$sku[$key]."'";
mysqli_query($sql);
In addition, you're using mysql_error here as well:
die('Could not update data: '. mysql_error());
P.S. Don't forget to escape any user input you are using in a database query! Though ideally you should use something like PDO or MySQLi prepared statements
This should be a full answer for you (with mysqli update):
<form name="form" method="post">
<table width="70%" border="5" align="center">
<tr>
<th scope="row">SKU</th>
<th scope="row">Item Description</th>
<th scope="row">Quantity</th>
<th scope="row">Unit Price</th>
</tr>
<?php
include('connect.php');
$result = mysqli_query("SELECT * FROM products")
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )) {
echo "<tr>";
echo '<td>'.htmlspecialchars($row['sku_id']).'</td>';
echo '<td>'.htmlspecialchars($row['description']).'</td>';
echo '<td><input name="qty['.htmlspecialchars($row['sku_id']).']" value="'.htmlspecialchars($row['quantity']).'"/></td>';
echo '<td><input name="price['.htmlspecialchars($row['sku_id']).']" value="'.htmlspecialchars($row['unit_price']).'"/></td>';
echo "</tr>";
}
?>
</table>
<input style="float:right" name="update" type="submit" id="update" value="Update"/>
</form>
<?php
if(isset($_POST['update']))
{
$qty = $_POST['qty'];
$price = $_POST['price'];
$stmt = $mysqli->stmt_init(); // <- mysqli class way of doing this
$stmt->prepare("UPDATE products SET quantity = ?, unit_price = ? WHERE sku_id = ?");
foreach($qty as $key => $value)
{
$data = array($qty[$key], $price[$key], $key);
$stmt->execute($sql, $data);
}
echo 'Update data successfully!';
}
?>
For testing purposes the processing of post can be changed to:
if(isset($_POST['update']))
{
$qty = $_POST['qty'];
$price = $_POST['price'];
//$stmt = $mysqli->stmt_init(); // <- mysqli class way of doing this
//$stmt->prepare("UPDATE products SET quantity = ?, unit_price = ? WHERE sku_id = ?");
foreach($qty as $key => $value)
{
echo "UPDATE products SET quantity = ".$qty[$key].", unit_price = ".$price[$key]." WHERE sku_id = " . $key . "<br/>\n";
//$data = array($qty[$key], $price[$key], $key);
//$stmt->execute($sql, $data);
}
echo 'Update data successfully!';
}
If you do a var_dump($_POST); you will see that your inputs have no values.
You need to specify the value on your form.
I would prefer to do this instead though:
echo '<input name="sku['.$row['sku_id'].']" value="'.$row['quantity'].'" />';
Then you can cycle through $_POST['sku'] and use the Key as the sku_id and the Value as the new value (quantity), to be updated
I'm getting questions from questions table in db.
I'm saving question_id and answer_value with an unique form_id and user_id to answers table in database.
I would like for the user to be able to update the form another day. So how can i get and display the form with answer_value already filled out based on the users earlier answer?
This is how i display questions from db:
<form action="/form/insert.php" method="POST">
$query = "SELECT * FROM questions where active=1 AND question_sort=1 ORDER BY sort_by";
$result = #mysqli_query($con, $query);
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$body = $row['question_body'];
$question_id = $row['question_id'];
echo '<tr>
<td class="question">'.$body.'</td>
<td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="0" ></td>
<td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="1" ></td>
<td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="2" ></td>
</tr>';
}
</form>
This is how i save every unicqe form to db:
$question_id = mysqli_real_escape_string($con, $_POST['question_id']);
$user_id = mysqli_real_escape_string($con, $_POST['user']);
$form_id = mysqli_real_escape_string($con, $_POST['form_id']);
$form_date = gmdate('Y-m-d H:i:s');
foreach ($_POST['answer_value'] as $question_id => $answer_id){
$sql="INSERT INTO answers (question_id, answer_value, user_id, form_id, form_date)
VALUES ({$question_id}, {$answer_id}, $user_id, {$form_id}, '$form_date')";
you have to loop through the values and match to the answer value you stored
<form action="/form/insert.php" method="POST">
<?php
$vals=array(0,1,2);
$query = "SELECT * FROM questions where active=1 AND question_sort=1 ORDER BY sort_by";
$result = #mysqli_query($con, $query);
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$body = $row['question_body'];
$question_id = $row['question_id'];
echo '<tr>
<td class="question">'.$body.'</td>';
foreach($vals as $x){
$s='';
if($x==$row['answer_value']){
$s="selected";
}
echo '<td class="answer"><input type="radio" name="answer_value['.$question_id.']" value="'.$x.'" '.$s.'></td>';
}
echo '</tr>';
}
}
?>
</form>
I know there are multiple questions here on SO regarding this same issue already and I've looked into them but didn't quite get a satisfying answer. So here goes my question,
I have a form which consists of a few textboxes and checkboxes. It looks like this,
The user can select multiple checkboxes. I'm trying to insert the values(not the displaying text string) of those checkboxes into a MySQL table. It should look like this,
One Service ID(SID) can have multiple Locations(Loc_Code). Those location codes (CO, GQ) are the values of the checkboxes.
I've written this following code so far.
<html>
<head>
</head>
<body>
<?php
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new ServiceID */
$query = "SELECT SID FROM taxi_services ORDER BY SID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row["SID"];
$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);
$new_id = $id_letter . $id_num;
//Selecting locations
$query = "SELECT Loc_Code, Name FROM districts";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<?php
if(isset($_POST["savebtn"]))
{
//inserting the new service information
$id = $_POST["sid"];
$name = $_POST["name"];
$cost = $_POST["cost"];
if($_POST["active"] == "on") $active = 1; else $active = 0;
$query = "INSERT INTO taxi_services(SID, Name, Cost, Active) VALUES('$id', '$name', '$cost', '$active')";
$result = mysql_query($query, $conn);
//inserting the location details
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
if (!$result || !$result5)
{
die("Error " . mysql_error());
}
else
{
?>
<script type="text/javascript">
alert("Record added successfully!");
</script>
<?php
}
mysql_close($conn);
}
?>
<div id="serv">
<b>Enter a new taxi service</b>
<br/><br/>
<form name="servForm" action="<?php $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Service ID</td>
<td><input type="text" name="sid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" style="text-align:right" /></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="cost" style="text-align:right" onkeypress="return isNumberKey(event)" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="checkbox" name="active" /></td>
</tr>
</table>
</div>
<div id="choseLoc">
Locations <br/><br/>
<table border="0">
<?php
$a = 0;
while($row = mysql_fetch_array($result))
{
if($a++ %5 == 0) echo "<tr>";
?>
<td align="center"><input type="checkbox" name="checkbox2[]" value="<?php echo $row['Loc_Code']; ?>" /></td>
<td style="text-align:left"><?php echo $row["Name"]; ?></td>
<?php
if($a %5 == 0) echo "</tr>";
}
?>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</form>
</div>
</body>
</html>
It inserts the Service details correctly. But when it inserts location data, a problem like this occurs,
I selected 4 checkboxes and saved. The 4 location codes gets saved along with the service ID. But as you can see from the screenshot above, a bunch of empty rows gets inserted too.
My question is how can I stop this from happening? How can I insert the data from the checkboxes only I select?
Thank you.
One way would be to only loop over the checkboxes that were submitted:
//inserting the location details
foreach($_POST["checkbox2"] as $loc_id)
{
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
I reiterate here the SQL injection warning given above: you would be much better off preparing an INSERT statement and then executing it with parameters. Using PDO, it would look something like:
//inserting the location details
$stmt = $dbh->prepare('
INSERT INTO service_locations(SID, Loc_Code) VALUES(:id, :loc)
');
$stmt->bindValue(':id', $id);
$stmt->bindParam(':loc', $loc_id);
foreach($_POST["checkbox2"] as $loc_id) $stmt->execute();
from these sentence:
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
i find the problem is that the value of loc_code must be the last loction you selected. because in this loop, the value of loc_code will replaced everytime. if you want to insert all the location, you should put it on the one sentence, like INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id'), the value of $loc_id should be CO,GQ,GL.
This is happening because the checkboxes that weren't ticked still get posted, they just have empty values. Before you do your insert to service_locations just check if $loc_id is empty or not, only do the insert if it isn't.