This code now works to update each row of data individually if submit button is clicked.
Original issue was that I could not get each record updated individually and it was updating ALL rows instead of just the one matching the ID I wanted.
CONNECTIONS STUFF
<form method='post'>";
$query="SELECT * FROM table WHERE approved='no'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
echo "<p>$count pending approval.</p>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$id=$row['id'];
$name = $row['name'];
$extra = $row['extra'];
echo "
<table>
<tr>
<td>ID:</td>
<td>$id <input type='hidden' name='id[]' value='$id'></td>
</tr>
<tr>
<td>Name:</td>
<td>$name <input type='hidden' name='name[]' value='$name'></td>
</tr>
<tr>
<td>Extra:</td>
<td>$extra <input type='hidden' name='extra[]' value='$extra'></td>
</tr>
<tr colspan='2'>
<td>
<center><input name='submit' type='submit' value='Approve'></form></center>
</td>
</tr>
</table><br>
";}
if($_POST['submit']) {
$update = "UPDATE table SET approved='yes' WHERE id='$id' LIMIT 1";
if(mysql_query($update)) $count++;
else die("Error in query:<br>$sql<br>");
echo "<p><b>$name has been approved</b></p>";
}
?>
You have to move your update statement outside the while (($i < $num)) {...}.
Currently, that's inside the loop...
You are looping over each row, and then checking if the submit button was clicked, and if so updating the row.
The issue is that you dont identify which button was clicked and so each row is updated when any button is pressed. Try this:
if (isset($_POST['accepted']) && isset($_POST['id']) && $_POST['id'] == $id)
This will check to see if the submited form corresponds to the current row
The fault is in here:
...
<?php
if (isset($_POST['accepted'])) {
$query_update = "UPDATE mytable SET accepted='yes' WHERE id ='$id'";
$result_update=mysql_query($query_update);}
$i++;
}
mysql_close();
?>
....
$i is the run vairable to iterate over ALL rows. it only gets incremented when $_POST['accepted'] is set. And in this particular case, it's generateing an update for each and evry single row with an $id which has come from the databse instead of the current POST.
Thus: all records will be updated.
Modfify:
...
<?php
if (isset($_POST['accepted']) && isset($_POST['id']) ) {
$updateId = $_POST['id'];
$query_update = "UPDATE mytable SET accepted='yes' WHERE id ='$updateId '";
$result_update=mysql_query($query_update);
mysql_close();
}
$i++;
?>
....
Related
code:
<?php
if(isset($_POST['save']))
{
$comment1 = $_POST['comment2'].",".date('Y-m-d');
$comment2 = $_POST['comment2'];
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = '$comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
if($result==true)
{
echo "successfull";
}
else
{
echo "error!";
}
}
?>
<form method="post" name="myform">
<table>
<tr>
<th>comment1</th>
<th>comment2</th>
<th>Action</th>
</tr>
<?php
$sql = "select * from enquires2 ";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr>
<td>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>'>
</td>
<td>
<?php echo $row['comment1']; ?>
</td>
<td>
<input type='text' name='comment2' id='comment2' value=""/>
</td>
<td>
<input type ='submit' name='save' id='save' value='Save' />
</td>
</tr>
<?php
}
?>
</table>
</form>
In this code I want to update table enquires2 with unique id. In following image you see that table row having save button this is only one row similarly it have multiple row which having save button in each row. Now I want that when I click on save button of particular row only that row data will be update. How can I fix this problem ? Please help.
Thank You
You could use AJAX and jQuery to do this and send the data to a separate PHP file and assigning the $row['ID'] to a data-value attribute of the button,
$("#save-btn").click(function(){
id = $(this).attr(data-value);
***** rest of values here
$.ajax({
method: "GET",
data: {id: id, rest of: data here},
url: phpfile.php,
success: function(){
console.log("Success");
}
})
});
While in the PHP file you would take get the id like,
$_GET['id'], and same with the other values since we are using the GET method and then put them in the update query.
First of all, for security reason you need to change this query to a prepared statement see PHP MySQLI Prevent SQL Injection:
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = $comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
This line is bad anyway, you are missing a opening quote for $comment2.
$query = "update enquires2 set comment1 = '$comment1', comment2 = $comment2', s_date = '$s_datee' where id='$id'";
Are you sure $link is an actual mysqli link?
As for the html part, you need to mkae one form for each record. See the link posted HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?
alternatively you could do something bad like only adding the $id to evry field for every row (similar to:)
<input type ='submit' name='save[<?=$id;?>]' id='save' value='Save' />
and in the php code check witch key is set.
if(isset($_POST['save']) && is_array($_POST['save'])){
$id=key($_POST['save']);
}
You will need to replicate the bad thing for your comments as well but as a proof of concept you can run this snippet on phpfiddle.org
<?php
print_r($_POST);
if(isset($_POST['save']) && is_array($_POST['save'])){
echo key($_POST['save']);
}
?>
<html>
<form method='post'>
<input type='submit' name='save[1]' value='1' />
<input type='submit' name='save[2]' value='2' />
</form>
</html>
Wish i could provide you a really full answer but there's alot of work to be done on your code for it to be 'proper coding'. Again this becaome a matter of opinion beside the fact that your code is vunerable to sql injection and is NOT accepable.
Don't use your code at all for security vulnerability. Read more about sql injection Here. After all, For each row () create a form with a hidden input storing id of row .
I revised my code to make it work,create a nested table inside your td, so that tag will be accepted,
also see this link for a working reference,
HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?
<?php
if(isset($_POST['save']))
{
$comment1 = $_POST['comment2'].",".date('Y-m-d');
$comment2 = $_POST['comment2'];
$id = $_POST['id'];
$query = "update enquires2 set comment1 = '$comment1', comment2 = '$comment2', s_date = '$s_datee' where id='$id'";
$result = mysqli_query($link,$query);
if($result==true)
{
echo "successfull";
}
else
{
echo "error!";
}
}
?>
<table>
<tr>
<th>comment1</th>
<th>comment2</th>
<th>Action</th>
</tr>
<?php
$sql = "select * from enquires2 ";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr><td><table>
<form method="post" name="myform">
<tr>
<td>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>'>
</td>
<td>
<?php echo $row['comment1']; ?>
</td>
<td>
<input type='text' name='comment2' id='comment2' value=""/>
</td>
<td>
<input type ='submit' name='save' id='save' value='Save' />
</td>
</tr>
</form>
</table>
</td>
</tr>
<?php
}
?>
</table>
Here Is my problem: I do not get any error with my code but my problem is when i click the 'Delete Multiple' Button it does nothing not even reload the page.
Note: By The Way the redirect_to(); function i created so do not get confused by thinking that is a php function or anything
PHP Code:
display_errors(E_ALL);
if(isset($_POST['muldelete'])) {
$mul = $_POST['checkdelete'];
$sql = "DELETE FROM cmarkers WHERE id = " . $mul;
$result = mysqli_query($db, $sql);
redirect_to("elerts.php");
}
HTML Code:
<form action="elerts.php" method="post">
<table class="table table-striped">
<tr>
<td> </td>
<td>Date</td>
<td>Comment</td>
<td>Actions</td>
</tr>
<?php
$sql = "SELECT * FROM cmarkers";
$result = $db->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><input type="checkbox" name="checkdelete[]" value="<?php echo $row['id']; ?>" /></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['comment']; ?></td>
<td>DeleteEdit</td>
</tr>
<?php
}
?>
<input type="submit" name="muldelete" value="Delete Multiple" />
</table>
</form>
Thank You
If you need more info please let me know
First, your code contain some attention and placements errors.
input between <table> outer of td's is incorrect.
You can't make a multiple delete if you generate one form by value to
delete.
Fix them.
Getting Array of muldelete
To all the checked inputs, you must add the array field symbol
to clusterize the name "muldelete" to a post array.
<td><input type="checkbox" name="checkdelete[]" value="<?php $row['id']; ?>" /></td>
PHP side
Now you can fetch whole deletion array, like this:
if(!empty($_POST["muldelete"]))
{
$mul = join(',', $_POST['checkdelete']);
// Using IN() to make only one query for all records instead of multiple
// ex: IN(3, 4, 54, 8)
$query = "DELETE FROM cmarkers WHERE id IN(".$mul.")";
$result = mysqli_query($db, $query);
redirect_to("elerts.php");
}
Security
If ID's are integer value, you can prevent string injection into the sql query
$mul = array_map(function($id)
{
return intval($id);
}, $mul);
Your button is outside the <form></form> tags, so it is not related to the form elements or the form method at all. Instead of having a different form for each checkbox you should surround the entire table with the form tags thus ensuring that all the checkboxes and the button are in the same form.
<form method='post' action='elerts.php'>
<table class="table table-striped">
...all your table data including checkboxes...
<input type="submit" name="muldelete" value="Delete Multiple" />
</table>
</form>
I think because You are closing form tag earlier than submit button.
Try to put whole table into and should work.
PHP should looks like
display_errors(E_ALL);
if(isset($_POST['muldelete'])) {
$mul = implode(',',$_POST['checkdelete']);
$sql = "DELETE FROM cmarkers WHERE id IN(" . $mul.")";
$result = mysqli_query($db, $sql);
redirect_to("elerts.php");
}
In my table each and every row has a cell with a submit button.
Here is my code
<?php
# Init the MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("selfie") or die(mysql_error()) ;
# Prepare the SELECT Query
$selectSQL = 'SELECT * FROM `image_upload` INNER JOIN user_table
ON image_upload.user_id=user_table.user_id WHERE flag="0" ORDER BY timestamp DESC';
# Execute the SELECT Query
if( !( $selectRes = mysql_query( $selectSQL ) ) ){
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}else{
?>
<table border="2">
<thead id="head">
<tr>
<th id="head">User name</th>
<th>Category</th>
<th>Description</th>
<th>Image</th>
<th>Location</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
if (isset($_GET['submit'])) {
$mobile = $_GET['dmobile'];
$query = mysql_query("update image_upload set
flag='$mobile' " );
}
if (isset($_GET['submit'])) {
header("Location: imageManagement.php");
}
if( mysql_num_rows( $selectRes )==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysql_fetch_assoc( $selectRes ) ){
echo "<tr>
<td>{$row['user_name']}</td>
<td>{$row['category']}</td>
<td>{$row['description']}</td>
<td ><img src='uploads/".$row['image']."'width=300px height=200px></td>
<td>{$row['location']}</td>
<td><form class=\"form\" method=\"get\"><label></label><br/>
<input class=\"input\" type=\"text\" name=\"dmobile\" value=\" {$row['flag']}\" />
<br>
<input class=\"submit\" type=\"submit\" name=\"submit\" value=\"update\" />
</form></td>
</tr>\n";
}
}
?>
</tbody>
</table>
<?php
In here when do changes and click on submit button of one row each and every rows are updated. How can I give unique value for each and every submit button.
Comment to answer, since OP said it works.
OP: "It's work. Thank you very much.... :) – Lanka"
Add this to your form:
<input type=\"hidden\" name=\"the_id\" value=\"{$row['id']}\" />
then add:
$theid = $_POST['the_id'];
then,
$query = mysql_query("update image_upload set flag='$mobile'
WHERE id = '$theid' " );
You may need to play around with it a bit, in the hidden input that is.
This is based on having an "id" column of course.
N.B.:
You should validate the user input (even if it's a hidden field)
Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
As it stands, you are using a deprecated MySQL library, which leaves you open to SQL injection.
else{
$counter=0 ;
while( $row = mysql_fetch_assoc( $selectRes ) ){
$value="Update ".$counter ;
$counter++ ;
echo "<tr>
<td>{$row['user_name']}</td>
<td>{$row['category']}</td>
<td>{$row['description']}</td>
<td ><img src='uploads/".$row['image']."'width=300px height=200px></td>
<td>{$row['location']}</td>
<td><form class=\"form\" method=\"get\"><label></label><br/>
<input class=\"input\" type=\"text\" name=\"dmobile\" value=\" {$row['flag']}\" />
<br>
<input class=\"submit\" type=\"submit\" name=\"submit\" value=\"".$value."\" />
</form></td>
</tr>\n";
}
}
I do not think the question is clearly framed but by replacing the else part of your code with the above code you will get different values for submit button ie., update 0,update 1 and so on.. Hope this helps.
I have this deleting sql but can't seem to find out why it's not working :/
After trying to delete a checked row the if($result) does reload the page but the row is still there ... :/
Can someone please help me ?
What am I missing ?
<form name="delete_posts" method="post" action="">
<table class="all_posts">
<tr>
<td class="checkbox"><input type="checkbox" name="select_all" id="select_all" /></td>
<td class="post_title">Title</td>
<td>Auther</td>
<td>Posted</td>
<td>Updated</td>
<td>Category</td>
</tr>
<tr><td class="delete_posts" colspan="6"><input name="delete" type="submit"
id="delete" value="delete"></td></tr>
<?php
$post_set = get_all_posts();
while ($row = mysqli_fetch_array($post_set)){
echo "<tr>
<td><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=".$row['id']."></td>
<td><a href=\"edit_post.php?edit=".$row['id']."\">" .$row['title']. "</td>
<td>Auther</td>
<td>".date("d. M. 'y", strtotime($row["date"]))."</td>
<td>Update Date</td>
<td>".str_replace("_"," ",$row['category'])."</td>
</tr>";}
// Delete Posts
if(isset($_POST['delete'])){
$checkbox = $_POST['delete'];
$count = count($checkbox);
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM posts WHERE id = $del_id ";
$result = mysqli_query($connection, $sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=posts.php\">";
}
}
?>
</table>
</form>
Thanx for helping
Cheers
Chris
I think you have an error in your code where you retrive the checked row : instead of getting the checkbox values ($checkbox = $_POST['checkbox'];) you are getting the delete value ($checkbox = $_POST['delete'];).
Here is the corrected part :
if(isset($_POST['delete'])){
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM posts WHERE id = $del_id ";
$result = mysqli_query($connection, $sql);
}
My main issue that I am running into is basically this:
I have a while loop that generates results from a query. With the results that have been generated, I want the ability to update the table the original query was from.
The query produces the expected results, but the table is not being updated when I click the REMOVE button. I am also trying to find a solution for the results to be updated after the UPDATE query executes...
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'><input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/></td>
</tr>";
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='{$row['vin']}'";
mysql_query($removeSql) or die('check that code dummy');
}
}
mysql_close($connection);
?>
That's a submit button, will not work without form tag. You can't do it this way.
You can write the remove code on a separate page and convert that submit button to normal button and pass vin id on click of that button and call that page using ajax.
Or if you don't know ajax and want to do it on that page itself then do it this way :
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>
<form action="" method="POST">
<input type="hidden" name="vin_id" value="<?php echo $row['vin']; ?>">
<input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/>
</form></td>
</tr>";
}
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='".$_POST['vin_id']."'";
mysql_query($removeSql) or die('check that code dummy');
}
mysql_close($connection);
?>