can't delete from specific row from generate table from mySQL - php

Hye, i'm working on a small project of Inventory system. Everything is okay until this last part. I have included a delete button at the end of each row for user to delete any item of choice, but when user press the delete button, it deleted the last row of the table, instead of the row/item of choices, where is my mistake in my coding?
Thank you!
<?php
$result= mysql_query("SELECT * from Staff ORDER BY status");
$count=1;
while($row=mysql_fetch_array($result)){
?>
<tr>
<td align="left"><?php echo $count; ?></td>
<td align="left"><?php echo $row['staffId']; ?></td>
<td align="left"><?php echo $row['name']; ?></td>
<td align="left"><?php echo $row['address'];?></td>
<td align="left"><?php echo $row['pNum'];?></td>
<td align="left"><?php echo $row['status'];?></td>
<td align="left"><?php echo $row['type'];?></td>
<td><input type="submit" name="deleteStaff" value="Delete" onClick="displayMessage()">
<input type="hidden" name="staffId1" value="<?PHP echo $row['staffId']; ?>">
</td>
</tr>
</tbody>
<?php
$count++; }
if(isset($_POST['deleteStaff'])){
$id=$_POST['staffId1'];
$result=mysql_query("DELETE from Staff WHERE staffId='$id' ");
if($result){
echo '<script> location.replace("viewStaff.php"); </script>';
}
else{
?>
<script>
alert ("Fail to delete data")
window.location.href='viewStaff.php'
</script>
<?PHP
}
}
?>

I've encountered this error before as well. I think the error is happening since you're calling the same "onclick" function for each array result.
Instead, create a link to a page where you can run the php deletion script and pass the staffID into the URI and Get that in the php deletion script that you created.
example
<form action="deletion_script.php?staffid=<?php echo $staffid; ?>">
Put that inside of the td tag
Then in your deletion_script.php file, put something like this
<?php
//get staffid from URI
$staffid = $_GET['staffid'];
$sql="DELETE FROM $table_name WHERE staffid = '$staffid'"
$result = mysqli_query($connect, $sql);
if($result) {
//send back to the page you want
header("Location: ../inventory.php");
}
?>
This worked for me, and how I handle all situations like this from now on. You'll need to adjust the code a little to fit your set up.

since the name for the hidden field is the same for all rows being generated the post request is pulling the value of the last row( also "staffId1" ).
I recommend either using a individual form for each row in which case your code doesn't change as much or use js to get the required staffID using selectors

If you include the same hidden field (StaffId1) for every record it will contain more then one value.
You are now listening to the pressed SUBMIT so you don't need the hidden field. You can just get the value if the pressed SUBMIT.
Button
type="submit" name="staffId" value="<?php echo $id ?>"
Php
$id=$_POST['staffId'];

Related

Deleting Specific rows using PHP

I am trying to add a delete button to my note taking website project I am doing at school. Almost like a forum, where you would delete replies to a topic... I want to be able to delete individual notes. Currently I can delete, however it will only delete the most recent note (bottom of the notes table). How would I get it so the delete button deletes the note from the corresponding row, not just the bottom one.
The main interface (Where I believe the problem is)
$sql="SELECT noteID, title, note, timestamp FROM $tbl_name WHERE user='$currentuser' AND subject='$currentsubject'";
$result=mysql_query($sql);
?>
<table align="center" id="notes">
<tr>
<td width="10%"><strong>Title</strong></td>
<td width="10%"><strong>ID</strong></td>
<td width="50%"><strong>Note</strong></td>
<td width="10%"><strong>Time</strong></td>
<td width="10%"><strong>Delete</strong></td>
</tr>
<?php
// Start looping table row
while($rows=mysql_fetch_array($result)){
echo'
<br>
<tr>
<td>'.$rows['title'].'</td>
<td>'.$rows['noteID'].'</td>
<td>'.$rows['note'].'</td>
<td>'.$rows['timestamp'].'</td> ';
$todelete = $rows['noteID'];
$_SESSION['todelete'] = $todelete;
echo'
<td><form method="post" action="deletenote.php" ><input type="submit" name="submit" value="Delete" </td>
</tr>
';
}
ob_end_flush()
?>
Another way of doing it would be by just providing a delete link for each post:
// Start looping table row
while($rows=mysql_fetch_array($result)){
echo '<br>';
echo '<tr>';
echo '<td>'.$rows['title'].'</td>';
echo '<td>'.$rows['noteID'].'</td>';
echo '<td>'.$rows['note'].'</td>';
echo '<td>'.$rows['timestamp'].'</td>';
echo '<td>Delete</td>';
echo '</tr>';
}
Keep in mind that deletenote.php would have to verify that the user is signed in and has permission to delete the post.
First of all: where is your corresponding code/query regarding the specific use case (delete note)?
You are trying to submit a form without any parameters, I am assuming you are trying to use the session variable. However, this variable will always be set to the last loop-iteration. Therefore, I would recommend you to use this code sample:
// Start looping table row
while($rows=mysql_fetch_array($result)){
echo '<br>';
echo '<tr>';
echo '<td>'.$rows['title'].'</td>';
echo '<td>'.$rows['noteID'].'</td>';
echo '<td>'.$rows['note'].'</td>';
echo '<td>'.$rows['timestamp'].'</td>';
echo '<td><form method="post" action="deletenote.php" ><input type="hidden" name="noteID" value="'.$rows['noteID'].'"><input type="submit" name="submit" value="Delete"></form> </td>';
echo '</tr>';
}

How do I toggle a displayed database field with single click

I have a database table and one specific value is either a value of Yes or No represented by an icon of checkmark or X.
I want to be able to toggle this value with a single click rather then the current workflow where the user clicks the icon and then they are directed to update page where they toggle the value and then update.
The value is either Yes or No. I simply want to click it have the value change to the opposite value real time without refreshing.
Thank you
Here is the partial code for the display database, the field name is called 'enter'
<?php
include "db.inc.php";
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 15;
$sql = "SELECT * FROM ircb ORDER BY id DESC LIMIT $start_from, 15";
$rs_result = mysql_query ($sql);
$num_rows = mysql_num_rows($rs_result);
$query = mysql_query("SELECT * FROM ircb");
$number=mysql_num_rows($query);
while($rows=mysql_fetch_array($rs_result)){
<tr bgcolor='#9B9D9F'>
<td><?= $rows['totalt'] ?></td>
<td><?= $rows['service'] ?></td>
<td><?= $rows['item'] ?></td>
<td align="center">
<a href="edit_form1.php?id=<?= $rows['id'] ?>">
<img src="backgrounds/bg/<?= $rows['enter'] ?>.png" border="0">
</a>
</td>
</tr>
The edit.form1
<form method="post" action="update1.php">
<input type="hidden" name="id" value=<?php echo "$row[id]"?>">
<tr>
<td>Entered</td>
<td>
<input type="radio" name="enter"
value=Yes>Yes<input type="radio" name="enter" value=No checked>No
</td>
</tr>
<hr />
<tr style="height: 20px"><td></td></tr>
<tr>
<td align="right">
<input class="button" type="submit"
value="Update">
</td>
The problem you are having seems to be because you are redirecting to a page that has a form to do the update. Instead of using a form, you could use the link directly to do the trick. The best way to do it is to have the href lead to the exact same page that displays the table, but adding query parameters to tell the scripts to toggle the required row.
Using this, you could check in your PHP, before querying the database to display the tables:
if($_GET['toggle_id']){
//$_GET['toggle_id'] = the ID of the line to modify
//Use the same script as the form handler
}
So instead of waiting for a value of YES or NO, you would figure it out yourself using the current value:
$nextValue = $currentValue=='NO'?'YES':'NO';
That should cover most of the logic.

How to get the name/id of multiple buttons

I have gotten the id numbers of users from my database, and I want to make a button for each user. My code makes a table that shows all the IDs and creates a button for each one. I'm having trouble figuring out how to get the name of those buttons for use in other code. The error I am getting is "undefined variable" (in the 3rd line), which I am most likely getting because I am going at getting the button names wrong.
Basically, the $_POST in the third line is wrong (among perhaps other things). My question is how would one get the name (or id?) of the buttons I have made: how should I fix the $_POST or should I use something else entirely?
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST[$n])) header("location:" . $n . ".php");
}
?>
<div id="mod_user">
<table id='mod_table'>
<th class='ttop'>#</th>
<th class='ttop'>Page</th>
<?php
$result = $db->prepare("SELECT * FROM User");
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$n=$row["UserID"];
?>
<form action="" method="post">
<tr>
<td class='tben'><?php echo $n; ?></td>
<td class='tben'><button type='submit' name=<?php echo $n; ?> >Go here</button></td>
<br />
</tr>
</form>
<?php
} ?>
</table>
</div>
You can try like this:
<td class='tben'><button type='submit' name="usernames[<?php echo $n ?>]" >Go here</button></td>
So you can get button name from $_POST["usernames"] array as below
foreach($_POST["usernames"] as $username => $btn_value)
echo "$username => $btn_name";

Cannot insert checkbox value into database

Hello i'm a newbie in PHP language. So I hope u guys can be simple with me. I need to create like a attendance system for a meeting. Now I was stuck at one part. I need to add a staff from a department for every created meeting event. The staff name was already appear when I click from dropdown menu for every department that retrieve from database. Now I tried to select from the checkbox staff that I want to add with the meeting id. But nothing is happened when I click the submit button after checked the staff name. I want to add to a new table with the meeting id. display.php is code I create to appear the staffname and to check the checkbox and retrieve the record from user table . The checkbox.php is for insert the checked checkbox to a table meetingstaff. Please anyone help me..
Here I attached my PHP code
display.php
<label>Reference No:</label>
<label id="attach"><?php echo $_GET["refno"]; ?></label>
<form action="display.php?refno=<?php echo $_GET["refno"]; ?>" method="post">
<?php do { ?>
<form action="checkbox.php?refno=<?php echo $_GET["refno"]; ?>" method="post">
<tr >
<td><div align="center"><input name="chkl[]" type="checkbox" id="checkbox[]" value="<? echo $row_Recordset4['staffname']; ?>"></td>
<td><div align="center"><?php echo $row_Recordset4['staffname']; ?></div></td>
<td><div align="center"><?php echo $row_Recordset4['staffno']; ?></div></td>
</div></td>
</tr>
<?php } while ($row_Recordset4 = mysql_fetch_assoc($Recordset4));?>
checkbox.php
<label>Reference No:</label>
<label id="attach"><?php echo $_GET["refno"]; ?></label>
<?php
$checkbox1 = $_POST['chkl'];
if($_POST["Submit"]=="Submit")
{
for ($i=0; $i<sizeof($checkbox1);$i++) {
$query="INSERT INTO meetingstaff (staffname, staffno) VALUES ('".$checkbox1[$i]."')";
mysql_query($query) or die (mysql_error());
}
echo "Record is inserted";
}
?>
You need to INSERT a second parameter, or remove , staffno from the first part of the INSERT statement. You are passing just one value, but instructing for two columns.
So change your:
INSERT INTO meetingstaff (staffname, staffno) VALUES ('".$checkbox1[$i]."')
to either
INSERT INTO meetingstaff (staffname) VALUES ('".$checkbox1[$i]."')
or perhaps
INSERT INTO meetingstaff (staffname, staffno) VALUES ('".$checkbox1[$i]."', ".$i.")

issue when inserting data in DB using submit button

i define below codes to show my products on website. I fetch my products details from Database.
When i click on the enquiry submit button it is not selecting the same id and inserting another product id in to database. Please see below codes which i use to send details in database using enquiry Submit Button
Please see below the updated codes, these are all codes which i am using to inserting data when clicking on enquiry submit button
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
</tr>
</table>
</td><br>
<?php
endwhile;
if($_REQUEST['enquiry'])
{
mysql_query("insert into orders values('$userid','$productid','$productprice')");
}
?>
Your table in your mysql database probably has the columns in a different order. To make sure, specify the columns in your insert query before specifying the values.
You're getting the wrong value for $productid because it's assigning the last value of it in your while loop, as your insertion code (and therefore your reference to it) is below that loop, you want to send the product id and price to the page accessible by $_REQUEST when the user clicks submit, to do this in your case you can use hidden form fields to store the values of each product, and a separate form for each element in your loop.
Also you want to put your submission code above your loop.
Depending where this data comes from you might want to escape it before inserting it in the database, I haven't in this example.
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
//check for submission and insert if set
if($_REQUEST['enquiry'])
{
//use the userid session for userid, and submitted values for productid and productprice
mysql_query("insert into orders values('$userid,'{$_REQUEST['productid']}','{$_REQUEST['productprice']}')");
}
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
//hidden form fields to store data to send to page
<input type="hidden" name="productid" value="<?php echo $productid;?>">
<input type="hidden" name="productprice" value="<?php echo $productprice;?>">
</tr>
</table>
</form>
<?php
endwhile;
?>

Categories