Deleting Specific rows using PHP - 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>';
}

Related

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

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'];

Sending a SQL command with one click of an HTML button through PHP

So, I have a basic PHP site that brings up a list of salespeople from a MySQL server when a selection from a drop-down box is submitted. I've set up a button to appear next to each result, and I want a php script to run when the button is clicked using MySQL data from that specific result. Everything works except the button that runs the second MySQL query. Here's an example of the table after the first query:
<table border="1">
<tr>
<td>Last name</td>
<td>First Name</td>
<td>Job Title</td>
<td>City</td>
<td>Client List</td>
</tr>
<tr>
<td>Bondur</td>
<td>Gerard</td>
<td>Sale Manager (EMEA)</td>
<td>Paris</td>
<td>
<form method="POST" action="empLookup.php">
<input type="submit" name="empLookup" value="Look up clients"
</td>
</tr>
</table>
By clicking on the button I would run a MySQL command like 'SELECT clients FROM blah WHERE employeeNumber = ?'
I don't have a problem with any of this except passing the value from the button to the PHP script.
This is what my PHP code looks like for handling the form submission and display of results. The button(s) in question are in the HTML table in the foreach loop.
<?php #this is the default php file for looking up Employees
$page_title = 'Our Associates by City';
require ('./pdoConn.php');
$sql = "SELECT DISTINCT city from Offices";
echo '<h1>Our Associates by City</h1>';
Type in a Name to view Years</a><br>';
//create the form
echo 'Please select a year: <br>';
echo '<form action="index.php" method="post">';
echo '<select name= "city">';
foreach($conn->query($sql) as $row)
{
//each option in the drop down menu is each and every year
//brought up by the query
echo '<option value ="'. $row['city'].' ">'. $row['city']. '</option>';
} //end of foreach
echo '</select>'; //end drop down menu
//now to create the submit button
echo '<br><input type="submit" name="submit" value="List"><br>';
echo '</form>'; //end of form
//This if statement runs when the submit button is clicked
if ($_SERVER[REQUEST_METHOD] == 'POST')
{
$flit = $_POST[city]; //the city variable from the HTML form will be used
echo '<br><br>';
$sql2 = "SELECT employeeNumber,lastName,firstName,jobTitle,city
FROM Employees,Offices
WHERE Employees.officeCode = Offices.officeCode AND city = ?";
$stmt = $conn->prepare($sql2);
$stmt->execute(array($flit));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'Contact any of our local staff: <br>';
//create a table of employees
echo '<table border="1"><tr><td>Last name</td><td>First Name</td>';
echo '<td>Job Title</td><td>City</td></tr>';
//time to populate the table, this loop runs for each entry
foreach($rows as $r)
{
echo '<tr><td>'.$r[lastName].'</td><td>'.$r[firstName].'</td><td>';
echo $r[jobTitle].'</td><td>'.$r[city].'</td><td>';
echo '<form method="POST" action="empLookup.php">';
//now to make the button which will search the employee's client list
echo '<input type="submit" name="empLookup" value="Look up clients"</td></tr>';
} //end foreach
echo '</table>';
} //end if server request post thing
?>
I does not completely understood your exact requirement but I think you want employee number into your button if this is your requirement then you can simply check this code
`echo '<input type="submit" name="empLookup" value="'.$r['emp_id_from_database'].'"</td></tr>';`
From your html code, your form looks empty.
You need to add the data to your html form. If you want to avoid the user to see you can use fields. Like it was in the comments said, use $variableName instead of ? in your query. Don't forget use \"$variableName\" to avoid mysql injections.
I took a second reading of your code: You realy should read a php book completly before you program stuff for productive company websites. There are beginner mistakes in your code. And some beginner mistakes leads to insecure websites. I hope this doesn't look an offense, but like an advise.

How to colect data from dynamicaly created php table

I'm new in php and webdevelop so i have simple problem.
Background of the story:
I have form in PHP (table) where I keep gifts list.
There are 3 column: number, gift description and info who booked gift (or if no one booked target gift, there is input text file that allow to book gift).
At the end of table there will be place to propose your own gift idea.
<?php
db_connect();
$result = mysql_query("SELECT GIFTS_ID, USER_DESCR, GIFT_DESCR FROM GIFTS");
$array = array();
while ($row_user = mysql_fetch_assoc($result))
$array[] = $row_user;
$howManyRows = mysql_num_rows($result);
db_close();
?>
<form action="" method="post">
table id="PersonList">
<thead>
<tr>
<th>Lp </th>
<th>Gift Description </th>
<th>Reservation </th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="2">
<input type="submit" name="send" value="Send">
</th>
</tr>
</tfoot>
<tbody>
<?php
foreach ($array as $gifts) {
echo '<tr>';
echo '<td class="number">' . "{$gifts['GIFTS_ID']}" . '</td>';
echo '<td class="description">' . "{$gifts['GIFT_DESCR']}" . '</td>';
echo '<td class="reservation">' . selectWhatToDisplay("{$gifts['USER_DESCR']}") . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</form>
<?php
function selectWhatToDisplay($USER_DESCR) {
if ($USER_DESCR == 'N')
{
return '<input type="text" name="reserv_data[]">';
}
else
{
return $USER_DESCR;
}
}
?>
As u see rows are created dynamicaly when user open website.
PROBLEM:
I want allow user to book more than one gift in single "Send" operation but I dont know how to collect data from dynamic created table: what rows was the target and what was data in single text field.
---EDITED---
My problem is that now i have multiple id named "reserv_data[]" as input field. Normal way to reach this kind of field is $_POST['name_of_field']. Now I dont know how to get (ie 5'th input file - 5'th means from 5'th row of table).
You can use javascript to select all the input fields and then check which of those have a value that's long enough(longer than 0 i guess).
Once you have the array of inputs you can organize them into a nice ajax call to the server.
All your inputs can be structed like this :
<input data-bookID="BOOK_ID" type="text">
This way you have all the information you need, the BOOK_ID can be generated dynamically when you construct the table.
I hope i understood your question properly :P

Is POST information from jquery $.post sent in parent page

I have a parent page which has a drop down list in it. using the onchange event, data is posted to a second page using $.post(). This page uses the posted variables to output mysql data with a checkbox for each line. This page output is then inserted into the parent page using jquery $('#DIV name').html(output).show();
The user can then see the mysql table rows with corresponding checkboxes. They then select the checkboxes they want and say delete. Delete is a form submit button.
My question is, when they click delete how do I take the form data from the second page and post it with that of the parent page so that I can then use $_POST[] to get the checkbox info and delete the selected table rows?
example of the parent page code is:
javascript/jquery
<script type="text/javascript">
function get(row){ //row being processed, defined in onchange="get(x)"
('getpeopleinjobs.php',{ //data posted to external page
postvarposition: form["position"+row].value, //variable equal to input box, sent to external page
postvarjob: form["job"+row].value, //variable equal to input box, sent to external page
postvarperson: form["person"+row].value, //variable equal to drop down list, sent to external page
postrow: row}, //variable equal row being processed, sent to external page
function(output){
$('#training'+row).html(output).show(); //display external results in row div
//popupWindow = window.open('t4.php?variable1Name=Vicki&variable2Name=Maulline','popUpWindow','height=400,width=1000,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=yes')
});
}
</script>
Form data is
<tr>
<td>
<?PHP echo $i; ?>
</td>
<td>
<input type=text NAME="position<?PHP echo $i; ?>" id="position<?PHP echo $i; ?>" style="border: 1px solid #2608c3;color:red; width=200px" value="<? echo mysql_result($resultpositionjob,$r,0);?>">
</td>
<td>
<input type=text NAME="job<?PHP echo $i; ?>" id="job<?PHP echo $i; ?>" style="border: 1px solid #2608c3;color:red; width=200px" value="<? echo mysql_result($resultpositionjob,$r,1);?>">
</td>
<td>
<SELECT NAME="person<?PHP echo $i; ?>" id="person<?PHP echo $i; ?>" style="border: 1px solid #2608c3;color:red; width=200px" onchange="get(<? echo $i; ?>);">
<OPTION VALUE=0 >
<?=$optionpeople?>
</SELECT>
</td>
<td onclick="train(<? echo $i; ?>);" style="color:grey; cursor: pointer;">
<div id="training<?PHP echo $i; ?>"><font color=grey size=2></div>
</td>
<td>
</td>
</tr>
<?PHP
$i++;
$r++;
}
?>
The second page or page called by jquery, the output is:
echo
"
<table border=0 width=400>
<tr>
<td width=20>
</td>
<td width=150>
<b>Position<b>
</td>
<td>
<b>Job<b>
</td>
</tr>
";
while($line = mysql_fetch_array($result))
{
echo "
<tr>
<td>
";
?>
<input type=checkbox name="delete[]" id="delete[]" value="<?php echo $rows['id']; ?>">
<?PHP
echo "
</td>
<td>
";
echo $line['position'];
echo "
</td>
<td>
";
echo $line['job'];
echo "
</td>
</tr>
";
}
?>
<tr>
<td>
<input type=submit name="update" id="update" value="Update">
</td>
</tr>
</table>
<?PHP
}
To repeat I want the table checkbox element from the second page posted with the form data of the parent page.
Is this possible as my testing hasnt given me any luck.
Am I doing something wrong or do I need to modify the jquery code?
Thanks as always for the assistance.
There is no second page. Really - you're loading HTML content from the second page, but it's being inserted into the parent page. All content, from your browsers perspective, is in the same page. The fields should be included as long as they're inside the DOM inside the element. Use the developer tools for your browser or Firebug for Firefox to make sure that the content is placed within the form element in the DOM. The developer tools should also be able to show you exactly which variables are submitted to the server when the form is submitted.
The 'action' parameter of 'form' will indicate where the content gets submitted (and it seems you've left that part out of your HTML, so it's impossible to say if you've left out or just not included it in the paste.

How to handle a dynamic table with dojo.query()

This is going to be a meaty question because I am not sure the best way to handle this.
I have a page that contains a number of dojo inline editors, to allow users to change values, when one entry had been changes a save button will appear to prompt the user to save the information.
The page has a number of rows, contained within DIV tags, which relate to a row in a database table.
<?php if($this->userjobdetails != null) : ?>
<?php foreach($this->userjobdetails as $employment) :?>
<div id="employ_<?php echo $this->escape($employment['historyid']);?>">
<table class="employment-table">
<tr>
<td><Strong>
<span dojoType="dijit.InlineEditBox" editor="dijit.form.TextBox" onchange="markEmploymentForUpdate();" id="cmpy_<?php echo $this->escape($employment['historyid']);?>"><?php echo $this->escape($employment['employername']);?></span>
</Strong>
</td>
<td align="left"><input dojoType="dijit.form.FilteringSelect" store="rolestore" searchAttr="name" name="role" id="roleInput_<?php echo $this->escape($employment['historyid']); ?>" value="<?php echo $this->escape($employment['jobrole']);?>"></td>
<td align="left">
<span dojoType="dijit.InlineEditBox" editor="dijit.form.TextBox" onchange="markEmploymentForUpdate();" id="jtitle_<?php echo $this->escape($employment['historyid']);?>"><?php echo $this->escape($employment['jobtitle']);?></span>
</td>
<td width="15px;">
<input type="hidden" value="<?php echo $this->escape($employment['historyid']);?>" name="employid" id="employid_<?php echo $this->escape($employment['historyid']);?>"/>
<img src="<?php echo $this->baseUrl();?>/images/site/msg/small/msg-remove-small.png" border="0" onmouseover="this.style.cursor='pointer';" onclick="removeEmployer('emply_<?php echo $this->escape($employment['historyid']);?>')"/>
</td>
</tr>
</table>
</div>
<?php endforeach;?>
When the user 'saves' the page I want to then using dojo.xhrPost post the data for the elements on the page, so that the database rows are updated.
How would I go about this, having multiple 'rows'??
Thanks
Take a look at dijit.form.Form — the second example shows how to validate a form and do whatever actions you like when user submits it. AFAIK, dijit.form.Form doesn't care how many fields it has, and collects them dynamically.

Categories