How to delete a record from HTML table? - php

I have this codes so far:
This form is generated during a query loop
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['breed'] . "</td>";
if($row['neuteredOspayed']=="1"){
echo "<td>" . "neutered" . "</td>";
}else
echo "<td>" . "spayed". "</td>";
echo "<td>" . $row['priceFee'] . "</td>";
if($row['housebroken']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
if($row['goodwithdogs']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
if($row['goodwithcats']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "</tr>";
}
echo "</table>";
Now, is there a way to put a link saying "delete" next to every result? For example next to the status field?
Here is what it's looking like:
To get this deleted I guess that I need to spot the record somehow. What I need is to take the name of the animal. For example, how can I get the value "Sparky" from the table and assign it to a variable? If I have the name I would be able to make the checks and run a query witch will delete the record.

You will have to use Javascript and AJAX.
Basically, you'll want to put a button in a cell, one per row, and when it's clicked, pass the id of the record to be deleted back to a PHP script via AJAX, then remove the record from the database. It should also hide the row when it is clicked.
I'd recommend using jQuery's .ajax(), as raw XHR is painful at best.
There is no way to do this with just PHP, because HTTP is stateless. Once your web page is loaded, the HTML and PHP parts are done, and fixed. You'll HAVE to use Javascript to make consecutive requests.
Alternatively, as bcmcfc points out, you can also just have a hyperlink to a script that will delete a record from your database.

You'd need something like this in your while loop:
echo '<td>Delete</td>';
Using the table's primary key would be better than the name though - is the name unique in the db? Assuming there is a PK and it's called id:
echo '<td>Delete</td>';

Php just is for page generation, once you have generated that table you cannot modify it.
You could, however, make a new get request, specifying a parameter with the row name to delete, you have to change your server php code to take in account this parameter, though.
The best, according to me, is using javascript: you assign a td id to each row and then you write a simple function in which you delete that row.

You have to submit the form and do this action....
<input type="submit" name="submit" value="Delete" />
After submit the form will redirected to some page. In that page you got all the posted values. In that you can delete the record by using the record id otherwise you use the name for appropriate record.
$query = "DELETE FROM table_name WHERE name='$_POST['name']'";
(or)
$query = "DELETE FROM table_name WHERE id='$_POST['id']'";
After this execution you have to redirect the URL to that page.
(or)
Delete
In this file you have to written like this...
$id = $_REQUEST['id'];
$query = "DELETE FROM table_name WHERE id='$id'";

//Add this form before the end of the while loop
<form action="#" method="post">
<input type="hidden" name="name" value="<?php echo $row['name']?>">
<input type="submit" name="delete" value="delete">
</form>
//Add this at the end of the coding
<?php
if(isset($_POST['delete']))
{
//database connection
$sql="DELETE FROM `table_name` WHERE `name`='{$_POST['name']}'";
$queryEXE=mysql_query($sql);
}
?>

You add a "elemID" attribute to each of your <tr>s and a new class that would be individual for each row (for example, elem+the id):
<tr elemId="12" class="elem12">...</tr>
Then, for the Delete link, you use AJAX to call the page that deletes the row from your DB, passing the elemID as an argument to this function:
function deleteRow(thisElemID) {
$.ajax({
url: yourURL,
data: {'elemID', thisElemID },
success: function() {
$('.elem'+thisElemID).remove();
}
});
}
More on $.ajax here.

Create another cell in your table and call ajax onclik of that button. Inside your ajax call delete the pecific row

Use a 'delete' form for each row.
The best way would be to add, for each row, a form with a submit button. Each form has a hidden field containing the id (or name, if you must) of the record to delete. Set the method of the form to 'post'.
Reasons why:
A delete link (a href) can be indexed and bookmarked easily. You
don't want pets to be deleted everytime Google drops by or a user is
browsing through their history.
A method='get' form also can cause
the url to be bookmarked and/or show up in the history. The method
with a form will work without Javascript altogether.
Apart from that,
Any solution (both forms and links) can easily be 'upgraded' to a solution with Ajax for a better user experience, but that's always an extra and no core functionality.
If you like, you can style the submit button to look like a link.
Use the post-redirect-get pattern if you implement this solution.
That is, assuming you want to actually remove the record from the database. If you just want to alter the HTML, a Javascript soliution would make more sense.

Related

Multiple actions for a single form

I have an html homepage which has a form. The form submit button sends the query to a single php page called First.php which gives the necessary data from the database in a tabular format. A single column from the table contains links as the contents of the column are too large to display on the same page. Once the link is selected, it gives the exact column information of only that query which I submitted on the homepage.
My general idea was to give two actions to the form action which can be used on two different pages but that to no result.
Here's the homepage :
<form action="First.php" action ="Second.php" method="POST">
<input type="text" size="90" name="search1">
<input type="hidden" size="90" name="search1">
<input type="submit" name="submit" value="Search..">
</form>
First.php after connecting to database and the firing the sql query :
if($ant>0)
{
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td><b href='Second.php'>Link</b></td>";
echo "</tr>";
}
}
Please do help me for the Second.php.
Any help would be deeply appreciated.
Thank you!
This is common pagination problem. You should use extra parameter in your form.
do something like
if($ant>0)
{
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td><b href='First.php?page=2'>Link</b></td>";
echo "</tr>";
}
}
You do not need a second action at all (and you cannot have one). What you need is to pass the id of the row to Second.php as a GET parameter. If you are not familiar with the concept, look it up because you will need it. A lot.
In Second.php you do not need the search parameters anymore because you are showing the details about a single row and you have its id. You just make a query to the DB to retrieve it by id and the old search becomes irrelevant.
In good conscience I have to say that the mysql_-something functions are a BAD idea. They have been removed in newer versions of php and are dangerous to use in the old ones. I strongly suggest that you use PDO and prepared statements ot at least the mysqli_ family of functions.

Trying to pass variable to URL in the edit link of show results

I have a show results page dumping the contents of a table. I've managed to echo in an edit link on each of my table rows. Edit kicks user to an update records page.
I'm trying to include the variables from the table row to the edit URL so I can do a $_GET URL param function on the update page and propagate the update form.
Here's what I have at the moment:
echo "<table>";
/* Get field information for all fields */
while ($row = mysqli_fetch_object($queryResult))
{
echo "<tr>";
echo "<td>" . $row->band_name . "</td><td>" . $row->votes . "</td><td><a href='vote.html?$band_name&$votes'>Edit</a></td>";
echo "</tr>";
}
First off, make sure that you declare your variables properly. It seems these guys are undefined in your url:
$band_name&$votes
Then format your url properly:
while ($row = mysqli_fetch_object($queryResult))
{
$band_name = $row->band_name;
$votes = $row->votes;
echo "<tr>";
echo "
<td>$band_name</td>
<td>$votes</td>
<td>
<a href='vote.html?band_name=".urlencode($band_name)."&votes=$votes'>Edit</a>
</td>";
echo "</tr>";
}
Are you sure its <a href='vote.html? HTML? you won't be able to parse this properly. Change it to vote.php
Then in vote.php, just get those values thru $_GET:
<?php
if(isset($_GET['band_name'], $_GET['votes'])) {
$band_name = $_GET['band_name'];
$votes = $_GET['votes'];
// rest of code mysqli etc. etc.
}
?>
You're not very clear on exactly what is not working, but in order for PHP to be able to get the query params they have to have a name.
if you change the following line and add parameter names, you should be able to access the data with $_GET or parse_str.
echo "<td>" . $row->band_name . "</td><td>" . $row->votes . "</td><td><a href='vote.html?band_name=$band_name&votes=$votes'>Edit</a></td>";

PHP Add button to view all the contents of entire record MySQL

Currently I have a query running that brings up all the contents of the 'products' table and the 'user' associated with the products. It prints on a table. I want to create a button, that brings up the entire records.
Please note that I must only be able to view the selected record only.. How would I go about this?
echo "<table border='1'>
<tr>
<th>user_id</th>
<th>user_name</th>
<th>selected_product</th>
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
echo "<td>" . $row['user_id'] . "</td>";
echo "<td>" . $row['user_name'] . "</td>";
echo "<td>" . $row['selected_product'] . "</td>";
So a button should appear for each record that is returned as a result. When I click this button another window should appear which shows the entire contents (for this record only) and the user associated.
How does the button know which record its associated with.
<a href="anotherpage.php?id=<?php echo $row['user_id']?>" ><button>View Details</button></a>
This will take you to another page.
Use get method tho get the id into php variable.
$userId = $_GET['id'];
And now use sql query to fetch all the data from the database for single user.
$userResult = mysql_query("SELECT * FROM userTable WHERE user_id = ".$userId);

How can I delete 1 selected row from a lot of tables in PHP (from mysql)?

I have a PHP function, to write out my tables from MYSQL. I've made a button, to delete the selected rows (named torles).
How can I delete with my 'torles' button, the row in which I'm pressing it?
function munkalapok(){
kapcsolat(); //connect to mysql, and write out all rows
$sql="SELECT * FROM munkalap ORDER BY id DESC";
$vissza=mysql_query($sql);
mysql_close(kapcsolat()); //close mysql
print "<div class='datagrid'><center>";
print "<table border='1' align='center'>";
print "<thead><th>Módosítás</th><th>Munkalapszám</th></thead>";
$i='1'; //for count rows
while ($sor = mysql_fetch_array($vissza)) {
print "<tr><tbody>";
print "<form method='POST'>".
"<input type='submit' value='$i. Törlés' name='torles'>".
"</form>" . "</td>";
//Create the button
if(isset($_POST['torles'])){
kapcsolat(); //open mysql
$parancs="DELETE FROM munkalap WHERE munkalapszam = '$munka'";
mysql_query ($parancs);
mysql_close (kapcsolat());
header("Location: ./Munkalapok.php");
}
print "<td>" . $sor['munkalapszam'] . "</td>";
print "</tbody></tr>";
$i++;
}
print "</table>";
print "</center></div>";
}
what is $munka, how did you get this..may be it should be for id..
So you can have a hidden field in your form and make it value as row id(whatever you have)
just try as:
print "<tr><tbody>";
print "<form method='POST'><input type='hidden' name='id' value='$sor[munkalapszam]'><input type='submit' value='$i. Törlés' name='torles'></form>" . "</td>";
//Create the button
if(isset($_POST['torles'])){
kapcsolat(); //open mysql
$munka=(int) $_POST['id']; //i did this for id
$parancs="DELETE FROM munkalap WHERE munkalapszam = '$munka'";
mysql_query ($parancs);
mysql_close (kapcsolat());
may this help you
In your code, you do something like this:
connect to SQL, get rows and print them
while printing
show a button
if this button is pressed, delete a row and redirect
end while
This is your first error.
Instead, your code logic should look something like this:
if there is posted data
delete the data
connect to SQL, get rows and print
Your main problem, (the one you are asking about), is that you create buttons, but no way to identify which row the button was pressed in.
Instead of adding the $i variable in the value of the button, you can add another input, which is hidden:
print '<input type="hidden" name="row_id" value="'.$i.'"/>';
This way, you will be able to find out which row the button was pressed for:
if (isset($_POST['torles'])) {
$id = (int) $_POST['row_id'];
// delete where id = $id (assuming that $i is an id)
}
Are you using IDs to identify records on your database? You should associate an ID to each record with the autoincrement function. That will be your Primary Key. Then use the record ID to identify the table row, and do not use that $i variable.
You should check out Database's Normal Forms. http://www.1keydata.com/database-normalization/first-normal-form-1nf.php
I'm hoping you have an id for every element in your db. And that the id is a primary key.
Saying that, modify
print "<td>" . $sor['munkalapszam'] . "</td>";
to
print "<td>" . $sor['munkalapszam'] . "<span id='".$sor['id']."' >X</span></td>";
In this way, every row in your table can be uniquely identified.The X is the delete symbol.
Next step would be to use JS to handle the click and sent the id to the server using ajax to delete the row.
$( "td" ).click(function() {
//write the ajax code here to send the id to the server.
});
This is not the most secure way to do this. But this would give you a basic idea on how to get started.
you can read about jQuery ajax here : http://api.jquery.com/jQuery.ajax/
jQuery click event : http://api.jquery.com/click/
In the backend you need a file called as delete.php or soemthing.Write the logic to delete a row using id in this file.Pass the id as argument through ajax to this.

Passing a <td> value to a php script

Sorry if this is a noob question, but I'm still getting up to speed with PHP and can't find an answer to this one.
I have a php script that queries a mySQL table and then builds an HTML table from the results. This all works just fine. As part of that script, I add a <td> to each <tr> that gives the user a chance to delete each specific record from the database, one by one, if they so choose.
To make this work, I have to be able to pass over to the php script the unique identifier of that record, which exists as one of the values. Problem is, I don't know how to pass this value.
Here is my php script that builds the HTML table:
while ($row = mysql_fetch_array($result)) {
echo
"<tr class=\"datarow\">" .
"<td id=\"id_hdr\">" . $row['id'] . "</td>" .
"<td id=\"name_hdr\">" . $row['name'] . "</td>" .
"<td id=\"btn_delete\">
<form action=\"delete_item.php\">
<input type=\"image\" src=\"images/delete.png\">
</form>
</td>" .
"</tr>";
}
So, somehow I either need to explicitly pass 'id' along with "delete_item.php" and/or find a way on the php side to capture this value in a variable. If I can accomplish that I'm home free.
EDIT: Trying to implement both suggestions below, but can't quite get there. Here is how I updated my form based on how I read those suggestions:
"<td id='btn_delete'>".
"<form action='scripts/delete_item.php'>".
"<img src='images/delete.png'>".
"<input type='hidden' id='uid' value='" . $row['id'] . "'>".
"<input type='submit' value='Submit'/>".
"</form>".
"</td>" .
Then, in delete_item.php, I have this:
$id = $_POST['uid'];
$sql = "DELETE FROM myTable WHERE id=$id";
$result = mysql_query($sql);
if (!$result) {
die("<p>Error removing item: " . mysql_error() . "</p>");
}
But when I run it, I get the error:
Error removing item: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '' at line 1
And one final thing: this approach gives me a button with the word 'submit' directly under my image. I'd prefer not to have this if possible.
Thanks again!
<form action=\"delete_item.php\">
<input type=\"hidden\" value=\"$row['id']\" name=\"uid\" >
<input type=\"image\" src=\"images/delete.png\">
</form>
The unique id is placed in a hidden input. You can get this value using
$_POST['uid']
But you need to submit the form
<input type=\"submit\" name=\"submit\" value=\"delete\" ">
You could use an anchor tag with parameter for id.
ie, www.example.com/delete.php?id=20
Now you could get that id on page delete.php as $_GET['id']
Using that you could delete the data from the table and return to the required page by setting up header
If you required you could use the same logic with AJAX and with out a page reload you could permenently delete that data. I would recommend AJAX

Categories