PHP - Delete multiple rows via Checkbox - php

I have the following code, which works to a certain degree:
if(isset($_POST['remove'])) {
$user = $_POST['user'];
$passcode = $_POST['passcode'];
$sql = "SELECT *
FROM admin
WHERE username = '" . $user . "'
and passcode ='".md5($passcode)."'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count==0) {
echo "Invalid Credentials";
} else {
include 'config.php';
$cnt=array();
$listCheck = "'" .implode("','", $_POST['checkbox']) . "'";
$sql6 = "DELETE FROM `customer` WHERE `name` IN ($listCheck)";
$delete = mysqli_query ($conn,$sql6);
}
Issue is, it only deletes 1 of the selected rows. How do I modify the code so it deletes ALL of the selected rows?
<input type="submit" name="remove" class="btn2" value="Delete Selected">
<div>
<?php
$query1 = "SELECT `name` FROM `customer` ORDER BY `name` ASC ";
$result = mysqli_query($conn, $query1);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value=" . $row['name'] . "></td>";
echo"</tr>";
}
echo "</table>";
echo "<br>";
?>
</div>

You can simply use one query to delete all records without the pain of for loop
include 'config.php';
$array = $_POST['checkbox'];
$listCheck = "'" . implode("','", $array) . "'";
echo $sql6 = "DELETE FROM `customer` WHERE `name` IN ($listCheck)";
$delete = mysqli_query ($conn,$sql6);
Also there is issue in this code. Replace the below line with your code
echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value='" . $row['name'] . "'></td>";

better go with foreach( $_POST['checkbox'] as $k => $v), it may not always be numbers and even if this way you do not have a loop for each possible in range but only for each selected checkbox.
Also have a look on prepared statements for SQL queries, you do not want to have possible injections.
Besides LIKE better be replaced by the exact comparison =.

Try the following code:
include 'config.php';
$array = $_POST['checkbox'];
$listCheck = "";
foreach($array as $arr) {
$listCheck .= "'" . urldecode($arr) . "',";
}
$listCheck = substr(trim($listCheck), 0, -1);
echo $sql6 = "DELETE FROM `customer` WHERE `name` IN ($listCheck)";
$delete = mysqli_query ($conn,$sql6);

This is something that caught my eye
echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value" . $row['name'] . "></td>";
Should be
echo '<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="'.$row['name'].'" ></td>';
The value of the checkbox is missing an =

Related

Php update multiple row with checkbox

Hello i would like to UPDATE all the row with a Boolean ( 1 ) when i check the checkbox , but i can't do it when i try.. He select and update all "$id" or update only the last $id of my cours table.
Someone can help ? :)
EDIT :
<form action='' method='POST'>
<?php
require 'inc/db.php';
$req = $pdo->query('SELECT * FROM cours WHERE isValid = 0' );
while ($row = $req->fetch(PDO::FETCH_ASSOC)) {
$originalDate = $row['date'];
$newDate = date("d-m-Y", strtotime($originalDate));
$id = $row['id'];
echo "<tr>";
echo "<td>" . htmlspecialchars($newDate) . "</td>";
echo "<td>" . htmlspecialchars($row['hours']) . "</td>";
echo "<td>" . htmlspecialchars($row['iduser']) . " / " . htmlspecialchars($row['lastname']) . " / " . htmlspecialchars($row['firstname']) . "</td>";
echo "<td>" . htmlspecialchars($row['courses']) . "</td>";
echo "<td><input type='checkbox' name='check[$id]' value='1' >" . $id . "</td> ";
print "</tr>";
}
print "</table>";
if(isset($_POST['check']) && count($_POST['check'] )) {
$ids = implode($_POST['check']);
$req2 = $pdo->prepare("UPDATE cours SET isValid = 1 WHERE id IN ({$ids})");
$req2->execute();
var_dump($_POST['check']);
}
?>
<button type="submit" name="send" class="btn btn-primary center-block" >send</button>
</form>
if(isset($_POST['check']) && count($_POST['check'])) {
$ids = implode(', ', $_POST['check']);
$sql = "UPDATE cours SET isValid = 1 WHERE id IN ({$ids})";
//run sql
}
Of course, it's still as vulnerable to sql injection as your current code. You'd want to either ensure all the ids are actually integers, or use parameters in your statement.
You may be having trouble debugging this, because you put your var_dump outside the loop. So you're only ever going to SEE the last id.

mysql insert record from existing table with insert button

Sorry if my english is not correct. I will try my best..
The question is how can I insert record from existing table with insert button. Everything work fine except variable $book. It records value 0 to database. Here is code..
//if the user press "INSERT BOOK" button there will be new record in database
<?php
$reader=$_SESSION['user_id'];
$book=$row['book_id'];
if (isset($_POST['update'])){
$sql = "INSERT INTO `read` (`read_id`, `book`, `reader`) VALUES (LAST_INSERT_ID(), '$book' '$reader')";
$result = mysql_query($sql) or die(mysql_error());
if ($result) {
echo " Yes, it works!";
}
else{
echo "noup!";
}
}
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
$result = mysql_query("SELECT * FROM book b JOIN `read` r ON (b.book_id = r.book) JOIN users u ON (r.reader = u.user_id) WHERE b.book_name LIKE '%" . $name . "%' or b.writer LIKE '%" . $name . "%' AND u.user_id !=". $_SESSION['user_id']);
$num_rows = mysql_num_rows($result);
if($num_rows>=1){
echo "<table id='table1'>
<tr>
<th>book_id</th>
<th>BOOKNAME</th>
<th>WRITER</th>
<th>PAGES</th>
</tr>";
while($row=mysql_fetch_array($result)){
echo "<form action=add_book.php method='post'>";
echo "<tr>";
echo "<td>" . $row['book_id'] . "</td>";
echo "<td>" . $row['book_name'] . "</td>";
echo "<td>" . $row['writer'] . "</td>";
echo "<td>" . $row['pages'] . "</td>";
//echo "<td>" . "<input type = 'hidden' name = 'hidden' value =" . $row['book_id'] . " </td>";
echo "<td>" . "<input class = 'field' type = 'submit' name = 'update' value = 'INSERT BOOK'>" . " </td>";
echo "</tr>";
echo "</form>";
}//WHILE LOOP
echo "</table>";
}
else{
echo "NO RESULTS";
}//else
}//if(preg_match..)
} //if(isset($_GET['go'])){
} //if(isset($_POST['submit'])){
?>

How do I get results from a multiple drop down menu?

To reduce the risk of sql injection I decided only to use preset drop down menus for users to query the database. I have a set of five drop downs that work well together with a single submit button and it opens the page it should but I'm not getting any data. I think I've tried everything that I can find and I suspect it is the select line that is wrong but I've tried dozens of variations without success. It seems that every tutorial shows something different and none of the ones I've found have helped.
The drop down I'm using is this:
<form action="test_result3.php" method="post">
<?php
mysql_connect('localhost', 'user', 'password');
mysql_select_db('database');
$sql = "SELECT DISTINCT Country FROM engravers Where Country <>'' AND Country IS NOT NULL ORDER by Country";
$result = mysql_query($sql);
echo "<select name\\='Country'>";
echo "<option value='$_POST'>Country</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Country'] . "'>" . $row['Country'] . "</option>";
}
echo "</select>";
$sql = "SELECT DISTINCT Year FROM engravers Where Year <>'' AND Year IS NOT NULL ORDER by Year";
$result = mysql_query($sql);
echo "<select name\\='Year'>";
echo "<option value='$_POST'>Year</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Year'] . "'>" . $row['Year'] . "</option>";
}
echo "</select>";
$sql = "SELECT DISTINCT Engraver1Surname FROM engravers Where Engraver1Surname <> '' AND Engraver1Surname IS NOT NULL ORDER by Engraver1Surname";
$result = mysql_query($sql);
echo "<select name\\='Engraver1Surname'>";
echo "<option value='$_POST'>Engraver</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Engraver1Surname'] . "'>" . $row['Engraver1Surname'] . "</option>";
}
echo "</select>";
$sql = "SELECT DISTINCT Designer1Surname FROM engravers Where Designer1Surname <>'' AND Designer1Surname IS NOT NULL ORDER by Designer1Surname";
$result = mysql_query($sql);
echo "<select name\\='Designer1Surname'>";
echo "<option value='$_POST'>Designer</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Designer1Surname'] . "'>" . $row['Designer1Surname'] . "</option>";
}
echo "</select>";
$sql = "SELECT DISTINCT Printer FROM engravers Where Printer <>'' AND Printer IS NOT NULL ORDER by Printer";
$result = mysql_query($sql);
echo "<select name\\='Printer'>";
echo "<option value='$_POST'>Printer</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Printer'] . "'>" . $row['Printer'] . "</option>";
}
echo "</select>";
?>
<input type="submit" />
</form>
This takes me to the php page test_results3 but it is blank.
<?php
mysql_connect('localhost', 'user', 'password') or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$query=("SELECT * FROM engravers WHERE $Country = $_POST['Country']", $Year = $_POST['Year'], $Engraver1Surname = $_POST['Engraver1Surname'], $Designer1Surname = $_POST['Designer1Surname]', $Printer = $_POST['Printer']);
while($result = mysql_fetch_array( $query ));
$num=mysql_numrows($result);
$i=0;
while ($i,$num){
$i++;
}
{
echo $result['Country'];
echo " ";
echo $result['Year'];
echo " Engraver: ";
echo $result['Engraver1Surname'];
echo " Designer: ";
echo $result['Designer1Surname'];
echo " Printer: ";
echo $result['Printer'];
echo " ";
$img_url = "http://www.engravedstamps.net/images/";
{
echo '<img src="'.$img_url.$result['Images'].'" />';
}
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
echo "<b>Searched For:</b> " .$find;
}
mysql_close();
?>
I seem to be getting more confused and frustrated by the hour with this. So far I've spent six weeks trying to write a three page search and display website and I don't feel like I'm any closer than when I started. Any help at all would be greatly appreciated.

How to insert different selected value from drop down list into database

Scenario : The administrator is to assign different companies to different student.
Problem : All student is given the same company of the last student in the form.
How do i make my hidden input work so that the correct selected drop down values of companies for each estudent to reflect correctly on the database?
$result = mysqli_query($con,"SELECT student_id, admin_no, name, GPA, gender FROM student_details WHERE jobscope1= 'Information Technology' ORDER BY `GPA` DESC; ");
$result2 = mysqli_query($con,"SELECT job_title FROM job_details WHERE jobscope='Information Technology' ORDER BY `job_title` ASC;");
/*options sections start*/
$options= '';
while ($row2 = mysqli_fetch_assoc($result2))
{
$options .='<option value="'. $row2['job_title'] .'"> '. $row2['job_title'] .'</option>';
}
/*options sections end*/
//return the array and loop through each row
while($row = mysqli_fetch_assoc($result))
{
$adminno = $row['admin_no'];
$name = $row['name'];
$gpa = $row['GPA'];
$gender = $row['gender'];
echo "<tr>";
echo '<input type=hidden name=admin_no value='. $adminno . '/>';
echo "<td>" . $adminno . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $gpa . "</td>";
echo "<td>" . $gender . "</td>";
echo "<td><select name='ddl' { myform.submit('') }'>".$options."</select></td>";
}
echo "</tr>";
The php form action :
$query = mysqli_query($con, "SELECT * FROM student_details WHERE jobscope1 = 'Information Technology';");
while ($row = mysqli_fetch_assoc($query))
$complist = $_POST['ddl'];
$result4 = mysqli_query($con, "UPDATE `student_details` SET `company`= '" . $complist . "' WHERE `jobscope1` = 'Information Technology';");
Try this:
//return the array and loop through each row
while($row = mysqli_fetch_assoc($result))
{
$adminno = $row['admin_no'];
$name = $row['name'];
$gpa = $row['GPA'];
$gender = $row['gender'];
echo "<tr>";
//changed here (this is called an input array which makes it hold multiple
//values with same name)
echo "<input type='hidden' name='admin_no[]' value='". $adminno ."'/>"; //edited
echo "<td>" . $adminno . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $gpa . "</td>";
echo "<td>" . $gender . "</td>";
//changed here too
echo "<td><select name='ddl[]' >".$options."</select></td>"; //edited
}
In your PHP:
if(isset($_POST['ddl'])){
foreach( $_POST['ddl'] as $index => $val ) //edited extra { here
{
$result4 = mysqli_query($con, "UPDATE `student_details`
SET `company`= '" . $val . "'
WHERE `jobscope1` = 'Information Technology'
AND `admin_no` = '".$_POST['admin_no'][$index]."';");
}
}
In this all your values will be updated (whether you changed any dropdown or not). If you want to limit only the changed dropdowns to be updated then you can have a hidden input variable which changes its value on change of dropdown and update your query only if the hidden input matches.

can't update mysql table with $_post data

Here is the page show table from database and every row has textbox, and b_id to update table.
$result2 = mysqli_query($con,"SELECT * FROM zahialga WHERE bid IN ($imp)");
while($row = mysqli_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['b_id'] . "</td>";
echo "<td>" . $row['materials'] . "</td>";
echo "<td>" . $row['num'] . "</td>";
echo "<td> <input type='text' name='sh_num[]' maxlength='10'></td>";
echo "</tr>";
echo "<input type='hidden' name='b_id[]' value='" . $row['bid'] . "'>";
}
echo "</table>";
echo "<input type='submit' value='Илгээх'/>";
this is update page.
$con=mysqli_connect("localhost","root","","login");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sh_id_query = mysqli_query($con,"SELECT sh_id FROM zahialga order by bid desc limit 1");
$sh_id1 = $sh_id_query->fetch_object()->sh_id;
$sh_id2 = $sh_id1 + 1;
$count = count(array_filter($_POST["sh_num"]));
for($i=0;$i<$count;$i++)
{
$insert = mysqli_query($con,"UPDATE table SET
sh_id='{$sh_id2}',
sh_num='{$_POST['sh_num'][$i]}'
WHERE bid = '{$_POST['$b_id'][$i]}'");
}
this is getiing Notice: Undefined index: $b_id error. What im missed?
BTW sorry about my bad english.
There should be no $ sign:
$_POST['b_id'][$i]
$insert = mysqli_query($con,"UPDATE table SET
sh_id='{$sh_id2}',
sh_num='{$_POST['sh_num'][$i]}'
WHERE bid = '{$_POST['$b_id'][$i]}'");
// ^ additional $ sign here
should be
$insert = mysqli_query($con,"UPDATE table SET
sh_id='{$sh_id2}',
sh_num='{$_POST['sh_num'][$i]}'
WHERE bid = '{$_POST['b_id'][$i]}'");

Categories