Checkbox Deleting - If statement inside For loop deletes wrong entries - php

I have a page which displays my database information. Through each loop, there is a checkbox printed that is to delete the associated entry if checked and submitted. The checkbox names are 'delete[]' and there is the hidden value which contains the row id is named 'id[]'.
This is the relevant part of my form:
<tr><td valign='top'>
<label class='amarillo med' style='color:#C00;'>Delete Section </label>
<input type='checkbox' name='delete[]' />
<input type='hidden' name='id[]' value='" . $row['about_id'] . "' />
</td></tr>
This is my php and query
$deleteCount = count($_POST['delete']);
for ($x = 0; $x < $deleteCount; $x++) {
if(isset($_POST['delete'][$x])) {
$sql = 'DELETE FROM about WHERE about_id = \''.$_POST['id'][$x].'\'';
$result = mysql_query($sql);
}
}
This is what happens.
If three rows are returned and I want to delete only the third, I check the third box and click submit. This deletes the first row that was returned. Again, if three rows are returned and I want to delete the first and third, I submit and the first two rows are deleted.
What it looks like is happening is for every checkbox that is checked, that many rows are deleted starting with the first. Any advice would be greatly appreciated.

The best and much easier way is to use
<input type="checkbox" name="delete[]" value="<?=$row['about_id']?>"/>
and then
foreach($_REQUEST['delete'] as $delID)
{
...
}

Use the following code
<tr><td valign='top'>
<label class='amarillo med' style='color:#C00;'>Delete Section </label>
<input type='checkbox' name='delete[$row['id']]' />
<input type='hidden' name='id[$row['id']]' value='" . $row['about_id'] . "' />
</td></tr>
where $row['id'] is the id of the row

Related

How to get the particular row value when click on edit button in php?

The following code is in tag_show.php.I have to show all the data from the database and I am trying to edit the database from php code so i form the edit button at the end of all row in html table.
echo"<br><br><br><br>
<table border='6' style= 'background-color: #FFFFE0; color: #761a9b; margin: 2 auto;'>
<thead>
<tr>
<th>tag_title</th>
<th>description</th>
<th>show_in_welcome</th>
<th>status</th>
</tr>
</thread>
<tbody>";
while($row = mysqli_fetch_assoc($get_detail))
{
$_SESSION['tag_title'] =$row['tag_title'];
$_SESSION['description'] =$row['description'];
$_SESSION['show_in_welcome'] =$row['show_in_welcome'];
$_SESSION['status']=$row['status'];
echo
"<tr>
<td>{$_SESSION['tag_title']}</td>
<td>{$_SESSION['description']}</td>
<td>{$_SESSION['show_in_welcome']}</td>
<td>{$row['status']}</td>
<td><form action='edit.php' method='POST'><input type='hidden' name='tag_title' value='".$row["tag_title"]."'/><input type='submit' name='submit-btn' value='edit' /></form></td>
</tr>\n";
}
and the edit.php is
<?php
session_start();
echo"<form action='tag_show.php' method='post'>
<br><br><br>
Tag Title<br><input name='tag_title' type='text' value='{$_SESSION['tag_title']}'><br><br>
Description <br><input name='description' type='text' value='{$_SESSION['description']}'><br><br>
Show in welcome<br><input name='show_in_welcome' type='text' value='{$_SESSION['show_in_welcome']}'><br><br>
Status<br><input name='status' type='text' value='{$_SESSION['status']}'> <br><br>
<input name='submit1' type='submit' value='Update'>
</form>";
?>
but the $_SESSION returns the last row value in HTML table. But i want the receptive row value when i click on edit button.
You don't need a session variable to pass the value to edit.php file.
Hope there is a unique key to identify the record from database. I assume it as recordid. Pass this value to edit.php as a query string
tag_show.php
$output = '';
while($row = mysqli_fetch_assoc($get_detail)){
$output '<tr>
<td>'.$row['tag_title'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['show_in_welcome'].'</td>
<td>'.$row['status'].'</td>
<td>edit</td>
</tr>';
}
In edit.php, you can get the recordid from query string and retrieve the data from database to populate the form
<?php
if($_GET['editid']!=''){
//get record corresponding to the 'editid' from database
//I assume the record is for and store in a variable $editdata
?>
<form action="tag_show.php" method="post">
<br><br><br>
Tag Title<br><input name="tag_title" type="text" value="<?=$editdata['tag_title']?>"><br><br>
Description <br><input name="description" type="text" value="<?=$editdata['description']?>"><br><br>
Show in welcome<br><input name="show_in_welcome" type="text" value="<?=$editdata['show_in_welcome']?>"><br><br>
Status<br><input name="status" type="text" value="<?=$editdata['status']?>"> <br><br>
<input name="submit1" type="submit" value="Update">
</form>
<?php
}
?>
Looks like you are never updating the session data with the information received from the form. You will need something like this somewhere in your code.
$_SESSION['tag_title'] = $_POST['tag_title'];
$_SESSION['description'] = $_POST['description'];
$_SESSION['show_in_welcome'] = $_POST['show_in_welcome'];
$_SESSION['status']= $_POST['status'];
A few things to consider.
Make sure your db info does not overwrite the values after user submits form.
Always sanitize/validate user input before using it (unlike the above code, since it's just an example).
here session make no sense. each time loop runs previous value replaced therefore you are getting last value. Instead of you can use the concept of query strings. Instead of Printing Form print a anchor tag
<a href='file.php?id='.$row["tag_title"]>Edit</a>
Being your tag_title unique.
if(isset($_GET['id))
{
$id = $_['id']
// Your code based on id
}
Now using id run mysql query and select desired data and display in form
Certainly your code will return the last row as the session array overwrites the previous row's value after every iteration.
Make the session array as multi dimensional like $_SESSION[$id]["tag_title"] and then in your edit.php refer to the session array using the id value.
$_SESSION[$id] = array('tag_title' => $row['tag_title'], 'description' => $row['description'], 'show_in_welcome' => $row['show_in_welcome'], 'status' => $row['status'])
Then increment the $id after each iteration.

Using an Update SQL query in a foreach loop in PHP

I am trying to create a table showing multiple users data. The data in the table will then be able to be edited and updated. Below is an example of the way the form is laid out:
echo "<form action=AdminUpdateLecInfo.php method=post>";
while ($return = mysql_fetch_assoc($result)) {
$phonenumber = "$return[PhoneNumber]";
$number = str_pad($phonenumber, 11, "0", STR_PAD_LEFT);
echo " <tr class='data'>
<input type='hidden' name='id'".$return['ID']."'' value= '".$return['ID']."' />
<td class = 'title'><input class = 'title' type='text' name='title'".$return['ID']."'' value= '".$return['Title']."' /></td>
}
echo "</table>
<input class='submit' type='submit' value='Update Info' />
</form>
Once the table is created the information is passed to the 'update.php' script.
$sql="UPDATE completeinfo SET Title='".$_POST['title'][$return['ID']]."'
WHERE ID = '".$_POST['id'][$return['ID']]."'";
header("Location:Home.html");
The problem I'm having is that I need to add the '".$return['ID']."' to the name of each input field so that not all users details are updated with the same values. I am unsure if I need to apply a foreach loop around this query so that it applies to each user and updates their details. Currently however the update query is not working presumably because the post method is not fetching the values from the form correctly.
Your problem is the name of your fields, use that :
$return_id = $return['ID'];
echo "
<tr class='data'>
<td class = 'title'>
<input type='hidden' name='id$return_id' value='$return_id' />
<input class='title' type='text' name='title$return_id' value='$return_id' />
</td>
</tr>";
Before doing your mysql update, do var_dump($_POST);, you'll be shown the content of the HTTP POST parameters so you can see what they are and how to use them in the query.
You have to use the names of your text fields as array so you can iterate your array
name='title'".$return['ID']."'
name='id'".$return['ID']."'

PHP Mysql - Delete button keeps on deleting latest row

When i run into a glitch, I always find find the answer on StackOverflow, but this time, although I'm sure the fix is easy, I just can't seem to get it right !
Basically, i'm trying to add a "delete" button next to each row fetched from my mysql database. The users should be able to delete a specific post, if needed.
When i hit the delete button, it's always the latest row that gets deleted. So i guess there's something wrong with the value passed in each row : seems like they're overridden by the latest one.
Below's my code:
<?php
$table = query("SELECT post, postid FROM post_list WHERE id = ? ORDER BY
time DESC LIMIT 15", $_SESSION["id"]);
foreach ($table as $row)
{
$post = $row["post"];
$postid = $row["postid"];
echo ("<table>");
echo ("<tr>");
echo("<td>" . $post . "</td>");
echo("</td>")?>
<div id="posteraser">
<form action='' method='post'>
<input type='hidden' name='postid' value='<?php echo $postid?>'>
<input type='submit' name='posteraser'>Delete</input>
</form>
</div>
<?php
echo ("</td>");
echo ("</tr>");
echo ("</table>");
echo '<hr>';
}
?>
And below on the same page, there's the delete button code:
<?php
if(isset($_POST['posteraser']))
{
$sql = query("DELETE FROM post_list WHERE postid = '$postid' ");
redirect ('home.php');
}
?>
Any help/tips will be much appreciated !
Thanks a lot !
You have to pass here the $_POST['postid']
if(isset($_POST['posteraser'])){
$postid = $_POST['postid'];
$sql = query("DELETE FROM post_list WHERE postid = '$postid' ");
redirect ('home.php');
}
OR as procedure way
$sql = query("DELETE FROM post_list WHERE postid = ? ",$postid);
A developer should always be aware of the HTML code they create with their PHP code.
It's essential thing.
As a matter of fact, HTML code is the very result of our efforts. NOT nice picture on can see in the browser windows - it's browser's job - but the very HTML code.
So, if you bother to see into generated code, you would discover something that can be boiled down to
<input type='hidden' name='postid' value='1'>
<input type='hidden' name='postid' value='3'>
<input type='hidden' name='postid' value='4'>
<input type='hidden' name='postid' value='5'>
<input type='hidden' name='postid' value='9'>
Do you have any questions why you have only last value?
Speaking of solutions, you have two choices
create a separate form for the every row
mark the very Delete button with id.
<input type='submit' name='posteraser[<?php echo $postid?>]'>Delete</input>
for example
let's check the logic from select statement.
you are selecting postid and assigning it to a hidden element and when you press delete button
that hidden id is sent to server.
so form creating under for loop is
<div id="posteraser">
<form action='' method='post'>
<input type='hidden' name='postid' value='<?php echo $postid?>'>
<input type='submit' name='posteraser'>Delete</input>
</form>
</div>
but hidden element is creating with same name for each row.
so when you press delete button . first hidden id is sent to server.
and this hidden id is already newest as from your select statement.
so what's the solution for it..
either you should sent postid through get attaching it in your url so that you can identify
which delete button is pressed.
or create a logic to send only that id on which delete is pressed.
This looks wrong:
echo ("<tr>");
echo("<td>" . $post . "</td>");
echo("</td>")?>
The trailing </td> shouldn't be there. Something else perhaps?
Also, you don't show how postid gets into $_SESSION['id']

How to make sure at least one radio button is selected in each group, php

So I am trying to put together a voting system for each entry of a thread. Each entry gets a set of radio buttons (1, 2, 3) and a submit button is at the bottom. I want people voting to make sure they select one of the three radio buttons for each entry. I thought my code was working, but it's not. The last entry if it is selected, and all others aren't, it still says that its fine. But if I don't select the last entry it is working.
<form action="vote.php" method="POST" name="form1">
<? $sql = "SELECT * FROM contest_entries WHERE contest_id='$contest_id' ORDER BY id desc";
$result = mysql_query($sql) or trigger_error("SQL", E_USER_ERROR);
while ($list = mysql_fetch_assoc($result)) { $username=$list['username'];
$date=$list['date_entered'];
$pl_holder=$list['place_holder1'];
$contest_entry_id=$list['id'];
echo "1<input name='attending[$contest_entry_id]' type='radio' value='1'>
2<input name='attending[$contest_entry_id]' type='radio' value='2'>
3 <input name='attending[$contest_entry_id]' type='radio' value='3'> />";
}?>
<input type="submit" name="submit2" id="submit" value="Submit" />
So then on my vote.php page after hitting submit:
foreach($_POST['contest_entry_id'] as $key => $something) {
$example = $_POST['attending'][$key];
} if (!isset($example)) {
echo "You need to vote for all entries";
exit();
}else{
echo "success!";
}
It works except for the last entry, if the last entry is selected and others aren't it still thinks all entries have been selected
You should either add hidden value with the same name before radio options or query db for id's once again to do proper iteration through all options.
Check if every group is different than 0/isset() inside foreach loop.
Simple solution:
...
echo '<input type="hidden" name="' . attending[$contest_entry_id] . '" value="0">
1<input type="radio" name="' . attending[$contest_entry_id] . '" value="1">
2<input type="radio" name="' . attending[$contest_entry_id] . '" value="2">
3<input type="radio" name="' . attending[$contest_entry_id] . '" value="3">';
...
vote.php
foreach ($_POST['attending'] as $id => $value) {
if ($value == 0) {
echo 'You need to vote for all entries';
exit;
}
}
echo "success!";
BTW: Do not assign values to variable (like $example) if you're expecting that they doesn't exist - check them directly with isset($_POST[...])
foreach($_POST['contest_entry_id'] as $key => $something) {
$example = $_POST['attending'][$key];
How should this work? Your radio-group has the name attending[contest-id] - so $_POST['contenst_entry_id'] is not defined - is it?
Your if/else condition should be inside the foreach-loop brackets.
Appart from that I cannot tell you anything - please post errors or do print the global $_POST before iterating to see what is inside with var_dump() or print_r().

Order ofQuery with AJAX PHP and MySQL

Got a bit of a confusing situation, I have a form on my webpage that allows a user to enter information into a database...
Form
<form id="insertbill">
Total <input type="text" id="total" name="total" /><br />
Bill name<input type="text" id="bill-name" name="bill-name" /><br />
bill descriptiion <input type="text" id="bill-description" name="bill-description" /><br />
bill colour<input type="text" id="bill-colour" name="bill-colour" />
<input type="button" value="submit" onClick="insertBill();" />
</form>
This form then send the information via AJAX to my php which then inputs it into my DB
AJAX
function insertBill()
{
$.post('insert_bill.php', $('#insertbill').serialize(),
function(data) {
$('#bills').append(data);
});
};
PHP
$uid = $_SESSION['oauth_id'];
$bill = mysql_real_escape_string($_POST['total']);
$billname = mysql_real_escape_string($_POST['bill-name']);
$billdescription = mysql_real_escape_string($_POST['bill-description']);
$billcolour = mysql_real_escape_string($_POST['bill-colour']);
#Insert Record
$query = mysql_query("INSERT INTO `outgoings` (user_id, bill, bill_name, bill_description, bill_colour ) VALUES ('$uid', '$bill', '$billname', '$billdescription', '$billcolour')") or die(mysql_error());
Once this is done, the data is then returned to the webpage, with another form that allows the user to update the record...
Returned data/form
Print "<tr>";
Print "<th>total:</th> <td>".$bill . "</td> ";
Print "<th>bill name:</th> <td>".$$billname . "</td> ";
Print "<th>bill deposit:</th> <td>".$billdescription . "</td> ";
Print "<th>colour:</th> <td>". $billcolour . " </td></tr>";
echo "<th>edit:</th> <td>
<form id='bill-upd'>
<input type='hidden' value='". $billname."' name='billid' id='billid''>
Total <input type='text' id='total' name='total' /><br />
Bill name<input type='text' id='bill-name' name='bill-name' /><br />
bill descriptiion <input type='text' id='bill-description' name='bill-description' /><br />
bill colour<input type='text' id='bill-colour' name='bill-colour' />
<input type='button' value='submit' onClick='updateBill();' />
</form>
</td>";
My problem is that the returned form doesn't update, this is because I need to somehow find the id of the record that was inserted, place it into my form to be returned I think... I hope this isn't too confusing, but has anybody a better way of doing this without reloading the page?
here's what what you could include on your, insert_bill.php, view page:
<script>
var json=<?
$arr=array($bill, $billname, $billdescription, $billcolour);
echo json_encode($arr); ?>;
$('tr td:nth-child(0)').html(json[0]);
$('tr td:nth-child(1)').html(json[1]);
$('tr td:nth-child(2)').html(json[2]);
$('tr td:nth-child(3)').html(json[3]);
</script>
I guess the one outstanding issue is the "id" you says gets returned from your database. Can you explain a little further? Are their multiple forms on your insert_bill.php page? Regardless, you could put that $id into the array and feed it into and html() function like I did with the other variables.
You need to return the data from the database and then change, i imagine if you just need the id you must do.
in PHP
echo mysql_last_insert_id(); // so you get the last inserted id and "return" to the JS
In JS, inside the function data
You get the echo as a return and change the id
and then $("#billid").val(data)
I hope it help you

Categories