Deleting Mysql rows with checkbox - php

I've got a page where I render a table of values from Mysql using PHP and HTML.
I want to delete rows checked with a checkbox upon clicking a delete button. Unfortunately, nothing happens when clicking the button and I'm at a total loss as to where to look.
Code is below (database connection has been omitted, but it works).
<body>
<?php
$delete = $_POST['checkbox'];
$query = "SELECT * FROM Cards";
$result = mysql_query($query);
echo "<table>";
echo "<tr><td>Name</td><td>Quantity</td><td>Color</td><td>Type</td></tr>";
while ($row = mysql_fetch_array($result)){
echo "<tr><td><input type='checkbox' name='checkbox[]" . $row['id'] . "]'></td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Quantity'] . "</td>";
echo "<td>" . $row['Color'] . "</td>";
echo "<td>" . $row['CardType'] . "</td></tr>";
}
mysql_free_result($result);
echo "</table>";
?>
</body>
<tr>
<td colspan="5" align="center"><input name="delete" type="SUBMIT" id="delete" value="delete" action="POST"></td>
</tr>
<?php
if (isset($_POST['delete'])) {
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
for($i = 0; $i < $count; $i++) {
$id = (int) $checkbox[$i]; // Parse your value to integer
if ($id > 0) { // and check if it's bigger then 0
mysql_query("DELETE FROM Cards WHERE id = $id");
}
}
}
?>
<?php include "../footer.htm";?>

Try this:
<body>
<?php
$connect=mysqli_connect("Host","Username","Password","Database"); /* REPLACE NECESSARY DATA */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if (isset($_POST['delete'])){
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
for($i=0;$i<$count;$i++){
if(!empty($checkbox[$i])){ /* CHECK IF CHECKBOX IS CLICKED OR NOT */
$id = mysqli_real_escape_string($connect,$checkbox[$i]); /* ESCAPE STRINGS */
mysqli_query($connect,"DELETE FROM Cards WHERE id = '$id'"); /* EXECUTE QUERY AND USE ' ' (apostrophe) IN YOUR VARIABLE */
} /* END OF IF NOT EMPTY CHECKBOX */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
$query = "SELECT * FROM Cards"; /* SELECT FROM Cards TABLE */
$result = mysqli_query($connect,$query); /* EXECUTE QUERY */
echo "<form action='' method='POST'>"; /* SUBMIT PAGE ON ITSELF */
echo "<table>";
echo "<tr><td>Name</td><td>Quantity</td><td>Color</td><td>Type</td></tr>";
while ($row = mysqli_fetch_array($result)){ /* FETCH ARRAY */
$id=mysqli_real_escape_string($connect,$row['id']);
echo "<tr><td><input type='checkbox' name='checkbox[]' value='$id'></td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Quantity'] . "</td>";
echo "<td>" . $row['Color'] . "</td>";
echo "<td>" . $row['CardType'] . "</td></tr>";
}
mysqli_free_result($result);
echo "</table>";
?>
<tr>
<td colspan="5" align="center"><input name="delete" type="SUBMIT" id="delete" value="delete" action="POST"></td>
</tr>
</form>
<?php include "../footer.htm";?>
</body>
I've converted your code to MySQLi from the deprecated MySQL.
And used empty() function to determine a checked checkbox.
You forgot to put a <form> function for your html.
And also forgot to use value tag for your checkbox.
I have put explanations quoted in /* */ inside the code I have provided.

Try this:
<body>
<?php
$delete = $_POST['checkbox'];
$query = "SELECT * FROM Cards";
$result = mysql_query($query);
echo "<form method=post action=''>";
echo "<table>";
echo "<tr><td>Name</td>
<td>Quantity</td>
<td>Color</td>
<td>Type</td></tr>";
while ($row = mysql_fetch_array($result)){
$content .= <<< END
<tr>
<td><input type="checkbox" name="checkbox" value="{$row['id']}"></td>
<td>{$row['Name']}</td>
<td>{$row['Quantity']}</td>
<td>{$row['Color']}</td>
<td>{$row['CardType']}</td>
</tr>
END;
}
echo $content;
mysql_free_result($result);
?>
<tr>
<td colspan="5" align="center"><input name="delete" type="SUBMIT" id="delete" value="delete"></td>
</tr>
</table></form>
</body>
<?php
if (isset($_POST['delete'])) {
$checkbox = $_POST['checkbox'];
foreach($checkbox as $id) {
$id = (int) $id;
mysql_query("DELETE FROM Cards WHERE id = $id");
}
}
?>
<?php include "../footer.htm";?>

Related

How do I use foreach within a while loop

I have a script that displays all the values in a db table. I'd like to be able to update the price value of each row individually on clicking the update button but as it's in a while loop it's only updating the final value successfully. I realise this probably requires foreach but I can't figure where to code it within the loop to send the data from each row to the processing script on the next page. Can anyone help? Thank you!
Display script
<h2>Boiler Prices</h2>
<?php
$sql = "SELECT * FROM emb_prices_boilers ORDER BY id ASC";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
/* Start Form and Table ---------------------------------------------------------*/
echo "<form action='../admin/actions/set-boiler-price.php' method='post'>";
echo "<table id='boiler-prices'>
<tr>
<th>ID</th>
<th>Type</th>
<th>Boiler</th>
<th>Ref</th>
<th>Price</th>
</tr>";
/* Start Loop and Variables --------------------------------------------*/
while($row = $result->fetch_assoc()) {
$id = $row["id"];
$type = $row["type"];
$manufacturer = $row["manufacturer"];
$model = $row["model"];
$boilerref = $row["boilerref"];
$price = $row["price"];
// output data of each row
echo "
<tr>
<td>" .$id. "</td>
<td>" .$type. "</td>
<td>" .$manufacturer. " " .$model. "</td>
<td>" .$boilerref. "</td>
<td>£<input type='text' name='price' value='" .$price. "' /><input type='hidden' name='boilerref' value='" .$boilerref. "' /><input type='submit' value='update' /></td>
</tr>";
}
/* End Loop -------------------------------------------------------*/
echo "</table>";
echo "</form>";
/* End Table and Form -------------------------------------------------------*/
}
else {
echo "0 results";
}
?>
Processing script
<?php
$boilerref = $_POST['boilerref'];
$price = $_POST['price'];
if ($setboilerprice = mysqli_prepare($connection, "UPDATE emb_prices_boilers SET price = ? WHERE boilerref = ?")
) {
/* bind parameters for markers */
mysqli_stmt_bind_param($setboilerprice, "ds", $price, $boilerref );
/* execute query */
mysqli_stmt_execute($setboilerprice);
/* close statement */
mysqli_stmt_close($setboilerprice);
}
else {
echo "error: Failed to write to db";
}
?>
What you need is to create a separate form for each record. Remove <form>/</form> tags from the beginning and the end of <table> and use this code in your last td:
echo "
...
<td>
<form action='../admin/actions/set-boiler-price.php' method='post'>
£<input type='text' name='price' value='" .$price. "' />
<input type='hidden' name='boilerref' value='" .$boilerref. "' />
<input type='submit' value='update' />
</form>
</td>
</tr>";
With such mark up each form will send it's own data to your set-boiler-price.php and updating will work as you expect.

how to add foreach array in text input

I have a form in which I enter the name, surname and function (result one select), I display them with a foreach in a table.
I want to add a button to every foreach record that will load the first form with the data from the row but I can not.
Thanks for the help!
<?php
require_once 'functii/functii.php';
$r = functia();
$options = "";
while ($row = mysqli_fetch_array($r)) {
$options = $options . "<option>$row[0]</option>";
}
?>
<form method="POST">
<table id="add"><tr><td>Nume:</td><td><input type="text" name="nume"/></td></tr>
<tr><td>Prenume:</td><td><input type="text" name="prenume"/></td></tr>
<tr><td>Functia:</td><td><select name="functia"><?php echo $options; ?></select></td></tr>
<tr><td>Activ:</td><td><input type="radio" name="activ"/></td></tr>
<tr><td></td><td><input type="submit" name="adaugare" value="Adauga"/><input type="submit" name="modificare" value="Modifica"/></td></tr></table>
</form>
<?php
if (isset($_POST['adaugare'])) {
require_once 'functii/functii.php';
$n = $_POST['nume'];
$p = $_POST['prenume'];
$f = $_POST['functia'];
$r = adaug_utilizator($n, $p, $f);
}
require_once 'functii/functii.php';
$utilizatori = grid_utilizatori();
if (count($utilizatori) == 0) {
print 'Nu sunt utilizatori adaugati';
} else {
?>
<table id="view">
<thead><tr><th colspan="4">Utilizatori adaugati</th></tr>
<tr><th>Nume</th><th>Prenume</th><th>Functia</th></tr>
</thead>
<tbody>
<?php
foreach ($utilizatori as $utilizator) {
print "<tr>";
print "<td>" . $utilizator['nume'] . "</td>";
print "<td>" . $utilizator['prenume'] . "</td>";
print "<td>" . $utilizator['denumire'] . "</td>";
print "<td><input type='submit' name='modifica' value='Modifica'></td>";
print "</tr>";
}
if (isset($_POST['modifica'])) {
$_POST['nume'] = $utilizator['nume'];
$_POST['prenume'] = $utilizator['prenume'];
$_POST['functia'] = $utilizator['denumire'];
}
?>
</tbody>
</table>
<?php
}
?>
You can execute loop as follows:
<?php
foreach($utilizatori as $index => $utilizator){
?>
<input type='submit' name='modifica<?php echo ($index+1);?>' value='Modifica' class="clickBtn"></td>
<?php
}
?>
with above loop name attribute will be as modifica1, modifica2 etc.
Now, you want to fill information based on button clicked to the form shown at your top of code, I think so.
For this, you can use jQuery:
$('.clickBtn').click(function(e){
var buttonOfRowClicked = $(this).attr('name');
var rowNumber = buttonOfRowClicked.substr(8); // It will get 1,2,3 etc table row.
$('input[name=nume]').val($(tr:nth-child(rowNumber) td:nth-child(1).val());
$('input[name=prenume]').val($(tr:nth-child(rowNumber) td:nth-child(2).val()); //similarly fill other variables.
});
I have not check the code by executing. It is overview for you to run your code. I think idea is sufficient for you for direction how should your code works.

insert multiple rows of data by single submit button using php

How do I retrieve data from a SQL table, modify the data and store it in another database table with multiple rows & columns and with single submit button I want insert every rows at a time I don't know how to get that hidden value and work properly with that
<?php
include"connect_database.php";
if(isset($_POST['submit'])) {
$amt = $_POST['total'];
if($amt > 0) {
$qry = "INSERT INTO attendance(rollno, name, year, attendance, reason) VALUES "; // Split the mysql_query
for($i=1; $i<=$amt; $i++) {
$qry .= "('".$_POST["rollno$i"]."', '".$_POST["name$i"]."', '".$_POST["year$i"]."', '".$_POST["attendance$i"]."', '".$_POST["reason$i"]."' ),"; // loop the mysql_query values to avoid more server loding time
}
$qry = substr($qry, 0, strlen($qry)-2);
$insert = mysqli_query($dbcon, $qry); // Execute the mysql_query
}
// Redirect for each cases
if($insert) {
$msg = '<script type="text/javascript">alert("added");</script>';
}
else {
$msg = '<script type="text/javascript">alert("Server Error, Kindly Try Again");</script>';
}
};
if (isset($_POST['select']))
{
$sql = "SELECT * FROM data WHERE year='" . $_POST['yr'] . "'";
$myData = mysqli_query($dbcon, $sql);
$num = mysqli_num_rows($myData);
echo "<table border=1>
<tr>
<th>Rollno</th>
<th>Name</th>
<th>Year</th>
<th>Attendance</th>
<th>reason</th>
</tr>";
for ($i=0; $i <$num; $i++)
{
$record = mysqli_fetch_array($myData);
echo "<form action=smanage.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text name=rollno$i value=" . $record['rollno'] . " </td>";
echo "<td>" . "<input type=text name=name$i value=" . $record['name'] . " </td>";
echo "<td>" . "<input type=text name=year$i value=" . $record['year'] . " </td>";
echo "<td> "."<select name=attendance$i >
<option value=Present >present</option>
<option value=Absent >Absent</option>
</select>"."</td>";
echo "<td>". "<textarea cols=15 rows=2 name=reason$i placeholder=Enter reason ...></textarea>" . "</td>" ;
echo "<td>" . "<input type=hidden name=total value=" . $i-1 . "</td>";
echo "</tr>";
}
echo"</table>";
echo "<input type=submit name=submit value=save class=Button3>";
echo "</form>";
};
mysqli_close($dbcon);
?>
you are opening multiple forms, for each row in your table on.
This causes your html to be invalid, just start the form before displaying the table.
You could use this html
<table>
<?php
for ($i = 0; $i < $num; $i++) {
$record = mysqli_fetch_array($myData);
?>
<tr>
<td><input type="text" name="rollno[<?= $record['rollno'] ?>]" value="<?= $record['rollno'] ?>" </td>
<td><input type="text" name="name[<?= $record['rollno'] ?>]" value="<?= $record['name']?>" </td>
<td><input type="text" name="year[<?= $record['rollno'] ?>]" value="<?= $record['year'] ?>" </td>
<td><select name="attendance[<?= $record['rollno'] ?>]" >
<option value="Present" >present</option>
<option value="Absent" >Absent</option>
</select></td>
<td><textarea cols="15" rows="2" name="reason[<?= $record['rollno'] ?>]" placeholder="Enter reason ..."></textarea></td>
</tr>
<?php
}
?>
</table>
with this your values will every row will be put into the $_POST-Array, you can access the values via the indexes (I am guessing rollno represents the ID of the dataset).
When you really only want to insert all the values into a table, you can leave the index out. Meaning you could write
<td><input type="text" name="rollno[]" value="<?= $record['rollno'] ?>" </td>
Instead of
<td><input type="text" name="rollno[<?= $record['rollno'] ?>]" value="<?= $record['rollno'] ?>" </td>
You don't need the hidden field, you can just count the items in the array.
$total = count($_POST['rollno']);
<?php
include"connect_database.php";
if(isset($_POST['submit'])) {
$amt = $_POST['total'];
$rollnos= $_POST['rollno'];
if($amt > 0) {
$qry = "INSERT INTO attendance(rollno, name, year, attendance, reason) VALUES "; // Split the mysql_query
$i=0;
foreach($rollnos as $rollno) {
$qry .= "('".$rollno."', '".$_POST["name"][$i]."', '".$_POST["year"][$i]."', '".$_POST["attendance"][$i]."', '".$_POST["reason"][$i]."' ),"; // loop the mysql_query values to avoid more server loding time
$i=$i+1;
}
$qry = substr($qry, 0, strlen($qry)-2);
$insert = mysqli_query($dbcon, $qry); // Execute the mysql_query
}
// Redirect for each cases
if($insert) {
$msg = '<script type="text/javascript">alert("added");</script>';
}
else {
$msg = '<script type="text/javascript">alert("Server Error, Kindly Try Again");</script>';
}
};
if (isset($_POST['select']))
{
$sql = "SELECT * FROM data WHERE year='" . $_POST['yr'] . "'";
$myData = mysqli_query($dbcon, $sql);
$num = mysqli_num_rows($myData);
echo "<table border=1>
<tr>
<th>Rollno</th>
<th>Name</th>
<th>Year</th>
<th>Attendance</th>
<th>reason</th>
</tr>";
for ($i=0; $i <$num; $i++)
{
$record = mysqli_fetch_array($myData);
echo "<form action=smanage.php method=post>";
echo "<tr>";
echo "<td>" . "<input type='text' name='rollno[]' value='" . $record['rollno'] . "'> </td>";
echo "<td>" . "<input type='text' name='name[]' value='" . $record['name'] . "'> </td>";
echo "<td>" . "<input type='text' name='year[]' value='" . $record['year'] . "'> </td>";
echo "<td> "."<select name='attendance[]' >
<option value='Present' >present</option>
<option value='Absent' >Absent</option>
</select>"."</td>";
echo "<td>". "<textarea cols='15' rows='2' name='reason[]' placeholder='Enter reason ...'></textarea>" . "</td>" ;
echo "<td></td>";
echo "</tr>";
}
echo "<input type='hidden' name='total' value='" . $i-1 . "'>";
echo"</table>";
echo "<input type='submit' name='submit' value='save' class='Button3'>";
echo "</form>";
};
mysqli_close($dbcon);
?>

Sending bcc emails only for selected checkbox values

I am trying to send the same email only to selected users. I am printing values from table and want to select specific users to send an email.
<form name="unos" action="mail-proizvodi.php" method="post">
<?
echo "<table border='5'>
<tr>
<th> </th>
<th>ID</th>
<th>NAZIV</th>
<th>ADRESA</th>
<th>DRZAVA</th>
<th>GRAD</th>
<th>EMAIL</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo '<td><input type="checkbox" name="email[]" value="' . $row['ID'] . '"></td>';
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['NAZIV'] . "</td>";
echo "<td>" . $row['ADRESA'] . "</td>";
echo "<td>" . $row['DRZAVA'] . "</td>";
echo "<td>" . $row['GRAD'] . "</td>";
echo "<td>" . $row['EMAIL'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" name="submit" value="submit">
</form>
my mail-proizvodi.php code
$mail=$_POST['email'];
echo "Dzenad catic";
$query= "SELECT `EMAIL` FROM `clanovi` WHERE ID='$mail[0]'";
if(sizeof($mail)>1)
{
for($i=1; $i<sizeof($mail); $i++)
{
$query.=" OR ID = '$mail[$i]' ";
}
}
$result=mysqli_query($con,$query);
while(FALSE!==($row=mysqli_fetch_row($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:test#test.ba?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
echo "Send" ;
Post I am receiving is an array. And when I do var_dump($mail) I get
array
0 => string '20' (length=2)
1 => string '30' (length=2)
Any help or advice is appreciated. Thanks in advance.
I am posting solution for the problem I had in case someone else face similar mistake.
$mail=$_POST['email'];
$query= "SELECT `EMAIL` FROM `clanovi` WHERE ID ='$mail[0]'";
if(sizeof($mail)>1)
{
for($i=1; $i<sizeof($mail); $i++)
{
$query.=" OR ID = '$mail[$i]' ";
}
}
$result=mysql_query($query);
if (!$result) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while(FALSE!==($row=mysql_fetch_assoc($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:prodaja#alternativa.ba?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
echo "Send" ;
mysql_free_result($result);

Updating data from checkbox clicked

My Code so far. The data gets pulled correctly
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Request");
echo "<table border='1'>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Prayer Request</th>
<th>Deactivate Request</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Reg_F_Name'] . "</td>";
echo "<td>" . $row['Reg_L_Name'] . "</td>";
echo "<td>" . $row['Reg_Request'] . "</td>";
echo "<td><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"".$rows['Reg_ID']. "\" /></td>";
echo "</tr>";
}
echo "</table>";
echo
"<form action='' method='post'>
<input type='submit' name='use_button' value='Update' />
</form>";
if(isset($_POST['use_button']))
{
echo "hey";
$del_id = $_POST['checkbox'];
$detectinglocations = 'your database table name';
foreach($del_id as $value){
$sql = "Update Request set Reg_Status=0 WHERE Reg_ID='".$value."'";
$result = mysql_query($sql);
}
}
mysqli_close($con);
?>
Nothing Happens when I Click Submit. I am wanting it to Update the reg_Status to 0 for every check box that is click. So whats my problem. Thank you in advance for helping!
try adding an input hidden field with same name as the checkbox name before each checkbox and with value 0 .
The checkbox doesnt get posted when not checked.

Categories