How to display a button for each row in a table - php

I have a MySQL database of booking records and I am displaying this in an HTML table. I was wondering how to add a button in every row of the table that will allow me to delete that row from the database.
<!DOCTYPE html>
<html>
<head>
<h2> All bookings </h2>
</head>
<body>
<table class='striped white'>
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Surname</th>
<th>Date</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
echo
"<tr>".
"<td>". $row['id'] . "</td>" .
"<td>". $row['firstName'] . "</td>" .
"<td>". $row['surName'] . "</td>" .
"<td>". $row['date'] . "</td>" .
"<td>". $row['timeSlot'] . "</td>" .
"</tr>";
}
} else{
echo 'no bookings';
}
?>
</tbody>
</table>
</body>
</html>

You'll need to add a cell with a URL that has code configured to run a DELETE command in your database. This is typically what atomic ID's are used for. Lets assume the above table is in a file called table.php. Given this, we can adjust your first table cell to the following:
...
"<td>". $row['id'] . "<br />Delete Row</td>" .
...
Now when you click this link you'll have a GET variable assigned in the $_GET superglobal array called "deleteId" that you can use to delete the row.
You'll want to place this above your table so that any deletions reflect in the table each time you reload the page.
if (isset($_GET['deleteId'])) {
// Sanitize input for SQL injection risk
$deleteId = $mysqli->real_escape_string($_GET['deleteId'])
if (!is_null($deleteId)) {
// Just an example, you will need to correct this query and optionally use parameters vs. directly putting the variable in the SQL string
$mysqli->query("DELETE FROM ... WHERE id = '$deleteId'");
}
}

Bedlams suggestions seems like a good solution.
However I would recommend to NOT delete anything from your database. I would add a column to my table 'Removed' with an integer 0 or 1.
1 = deleted
0 = not deleted (default)
When clicking the button in the table it updates the selected row's removed to 1.

I use bootstrap so this example uses that library.
If you want to add a confirmation modal, just simply replace bedlam's a href to something like:
Delete Row
Then add a button in that modal that will handle the deletion logic. You can use bedlam's a href in that modal.
<button type="button" id="delete">Delete</button>
You'll need to add some javascript to get the dynamic modal. Something like:
$("#whateveridyougiveyourmodal").on("shown.bs.modal", function(event){
var id = $(event.relatedTarget).data('id');
$(this).find("#id-hidden-input").val(id);
});
$("#delete").click(function(event){
var id = document.querySelector("input[name='id']").value;
// POST ID TO DELETE FOR EXAMPLE I'LL USE AJAX
$.ajax({
type: "POST",
data:{data: id},
url: "WHERE YOU WANT TO HANDLE DELETION LOGIC.php",
success:function(result){
console.log(result);
}
});
});
In your "WHERE YOU WANT TO HANDLE DELETION LOGIC.php" you'll want to accept the POST data with the super global "$_POST", or in this case "$_POST['data']".

Related

Opening user profile in new tab

I am displaying proclamations in a table and I want to make each row clickable which I kinda did with js onclick function (i can only click on the name but i want to apply this to whole row). Now I want to see details about proclamations in new tab. My question starts here. I want to get proclamation ID when I click on a row but no idea how to do it. Plus i am doing onclick with js and rest of it is php so it's getting kinda messy there. I know it's not the best way to do it so i need your advice about how can I solve this issue.
P.S. I am not very familiar with js, those js parts been taken from web tutorials. And the code below is the section where I display the search results.
<section id="results">
<div class="container">
<table>
<tr>
<th>Name</th>
<th>Where</th>
<th>From</th>
<th>Date</th>
<th>Price</th>
<th>Type</th>
<th>PId</th>
</tr>
<?php
if(isset($_POST['search_btn'])){
include_once "db_connect.php";
$from = $_POST['from'];
$where = $_POST['where'];
$date = $_POST['date'];
$type = $_POST['type'];
$procid = $_POST['proc_id'];
if(empty($from) || empty($where) || empty($date) || empty($type)){
header("Location: index.php?search=empty");
exit();
}else{
$sql = "SELECT * FROM proc WHERE p_from = '".$from."' and p_where = '".$where."' and type= '".$type."' ";
$query = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($query);
while ($rows = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
echo "<tr><td onclick='content(this)'>" . $rows['p_name'] . " " . $rows['p_surname']. " </td><td>" .$rows['p_from']. "</td><td>" .$rows['p_where']. "</td><td>" .$rows['p_date']. "</td><td>" .$rows['price']. "</td><td>" .$rows['type']. "</td></tr>" ;
}
echo "</table>";
}
}else{
echo "Error!";
}
?>
<?php
$fullUrl = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(strpos($fullUrl, "search=empty") == true){
echo "<p class='error'>You did not fill in all fields!</p>";
}
?>
</table>
</div>
</section>
<script>
function content(elem){
<?php
?>
window.open('procdetail.php');
}
</script>
In your JavaScript function that calls window.open, you need to call the second parameter which will be the target to open the window, adding _blank will open it on a new tab instead of the same window:
window.open('procdetail.php', '_blank');
Give JavaScript the data needed to handle your information.
Also, if your idea is to open the tab with JavaScript with the content specially for the row, then you should try returning the necessary information to it, for example, if you want to open a new window with the content of a user, then you must let know JavaScript which user id should open.
This is as easy as returning in an attribute for your row element the value of the user id which data is being outputted by PHP.
Do something like this in your inline PHP script:
echo "
<tr class='table-item' data-userid='USER_ID_VARIABLE_HERE'>
<td>" . $rows['p_name'] . " " . $rows['p_surname']. " </td>
<td>" .$rows['p_from']. "</td>
<td>" .$rows['p_where']. "</td>
<td>" .$rows['p_date']. "</td>
<td>" .$rows['price']. "</td>
<td>" .$rows['type']. "</td>
</tr>
";
And then in your JavaScript code you could use an event listener for every element in your DOM with class="table-item":
window.onload = () => {
let tableItems = document.querySelectorAll(".table-item");
tableItems.forEach((element) => {
element.addEventListener("click", (event) => {
//Handle your click event here
let userId = event.target.dataset.userid; //Your user id
window.open('procdetail.php?id=' + userId, '_blank');
});
})
}
This will open in a new tab the contents of the url given which is procdetail.php?id=userId. So then, in your procdetail.php file you must handle the $_GET["id"] variable to show the respective data.
Additional resources:
You can read more of the window.open method here.
Try this
link name
If you want to continue to use inline JavaScript, you will first need to change the onClick attribute to be on the <tr> element instead of the <td> element. Once that is done, you can use the same function you have to pass the proc_id to the URL in the window.open(); method you have set in the function.
HTML/PHP
echo '<tr onclick="content(\''. $rows['proc_id'] .'\')">';
Javascript
function content(ID){
window.open('procdetail.php?proc_id=' + ID, '_blank');
}
This will make each of the table rows a clickable element that links to procdetail.php?proc_id=<YOUR_ID>
There is a way to perform this in HTML as well, but you want to modify the CSS of the table elements so that there are not non-clickable dead zones in the table row.
Using your current method of the single line echo, you could use something similar to the code below. This will append the proc_id data as a URL parameter for procdetail.php to parse.
Notice that the code only includes p_name and p_surname. You would have to add each definition with the same method.
PHP
echo "<tr><td><a href='procdetail.php?proc_id=". $rows['proc_id'] ."' target='_blank'>". $rows['p_name'] . "</a></td><td><a href='procdetail.php?proc_id=". $rows['proc_id'] ."' target='_blank'>". $rows['p_surname'] ."</a></td></tr>";
CSS
table tr td a {
display:block;
height:100%;
width:100%;
}
table tr td {
padding-left: 0;
padding-right: 0;
}
Check out this thread on the issue. It includes a usable demo that is hosted in JSFiddle.

php while loop echoing element outside of looped content

The forum pages on my website use PHP to create a table and then use a while loop to populate it from the database. This works fine and always has but I have tried to move the anchor, 'link', tag from around the post's title to the entire first section of the post within the table. To do this it goes through the following steps:
Open the table tag [OUTSIDE OF LOOP]
Echo headers [OUTSIDE OF LOOP]
Start WHILE loop that makes another post section for every post found.
Create table row
Create table data
Echo content
Close table data
REPEAT STEPS 5-7 ONCE MORE for post date section
Close table row
close table [OUSTIDE OF LOOP]
It should make the links clickable on all of the first section and they should be within the table like this:
<table> <--- *THIS IS BEFORE THE LOOP, IT GETS RUN ONCE ONLY* -->
<WHILE *do this like 5 times or something*>
<tr>
<a *category link*>
<td>
*content for the 'td' which is taken from the DB*
</td>
<td>
*content for the 'td' which is taken from the DB*
</td>
</a>
</tr>
<ENDWHILE>
</table>
However, in practice they end up outside of the table as can be seen in this screenshot:
Could anyone please explain this and how to fix it?
echo '<table class="forumTable">
<tr>
<th>Category</th>
<th>Last topic</th>
</tr>';
while($row = mysqli_fetch_assoc($catResult)){
echo '<tr>';
echo '<a href="category.php?id=' . htmlspecialchars($row['catID']) . '"><td class="catDesc">';
echo '<h3>' . $row['catName'] . '</h3>' . $row['catDesc'];
echo '</td>';
echo '<td class="catTime">';
$getTops = "SELECT topicID, topicSubject, topicDate, topicCat FROM topics WHERE topicCat = " . $row['catID'] . " ORDER BY topicDate DESC LIMIT 1";
$topResult = mysqli_query($connect, $getTops);
if(!$topResult){
echo '<p style="margin-top: 75px;">The last topic could not be displayed, please try again later.</p>';
}
else{
if(mysqli_num_rows($topResult) == 0){
echo '<p>No topics</p>';
}
else{
while($topRow = mysqli_fetch_assoc($topResult)){
echo '' . $topRow['topicSubject'] . ' at ' . $topRow['topicDate'];
}
}
}
echo '</td></a>';
echo '</tr>';
}
echo '</table>';
Since the source page confirms that the anchors are where you placed them, but the browser moves them around, you can either :
- contain your links inside the td table cell
- use an alternative approach to add the link where you want it html - table row like a link
Did you try to get page not from browser? How it looks?
I think browser does not allow you to put <a> into <table> directly without <tr><td> </td></tr>

Sorting Column by clicking column header in php web page

I have one page which has a button that clicks and displays all the data from the database in the table with jquery. I need to sort the table by clicking the column head. problem is that i have is, the way the table is populated. see the code. I have php code which populates it. The columns are ID, Licence etc. So I need to sort it on based of column.
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "
my query from database to display all the values
";
$result= $dbh->prepare($query,array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$result->execute();
echo "<table id='abc' class='abcd' width='100%'><tr>"
. "<th id='mydata' class='myd' onclick='loadOrderedData(myd)'>ABC</th>"
. "<th>DEF</th>"
.......
. "</tr>";
while($data=$result->fetch(PDO::FETCH_ASSOC,PDO::FETCH_ORI_NEXT))
{
echo "<tr>"
. "<td>" . $data['ABC'] . "</td>"
. "<td>" . $data['DEF'] . "</td>"
.......
. "</tr>";
}
echo "</table>";
?>
it is displayed in a div which is hidden at first and then using jquery it is made un-hidden on the button click which fetches the data. Please help me with the viable solution.
I tried making <a href="#" > and making use of onclick method. It doesn't work, may be due to how it populates the data.
Pertaining to the ops question in comments...
an example query using order by...
SELECT * FROM `my_table` ORDER BY `price` ASC
.... this returns the results ordered by the values in the price column. using ajax you can use jQuerys .load function. and pass the url with a get variable for which column to sort by,
You'll need to give your < tr > an id, ill call the id 'data' and the columns you'll click would have an onclick="loadOrderedData(columnName)" attribute call load function like...
function loadOrderedData(orderBy){
$('#data').load('aPhpPageThatReturnsData.php?orderBy='+orderBy);
}
so in the file being called the query might look like
SELECT * FROM `my_table` ORDER BY `$_GET['orderBy']` ASC
//code to create new html for your data <tr> using sorted data
Hopefully that helps.
update ....
$result->execute();
?>
<table id='abc' class='abcd' width='100%'>
<tr>
<th class='myd' onclick='loadOrderedData("myd")'>ABC</th>
<th>DEF</th>
</tr>
<tr>
<td colspan="2">
<table id="myData">
<?php
while($data=$result->fetch(PDO::FETCH_ASSOC,PDO::FETCH_ORI_NEXT))
{ ?>
<tr>
<td><?=$data['ABC']?></td>
<td><?=$data['DEF']?></td>
</tr>
<?php
} ?>
</table>
</td>
</tr>
</table>

How to delete a record from HTML table?

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.

using php to fill in an existing table

I have a blank html table (column) on my page. I have a csv file with last years info for
that column available, but I don't want to initially write those values into the table
cells (because there might be new info which needs to be manually entered). I would like
to make a button which would populate this column. What would be the best way of going
about this? Since I want the info entered dynamically I would obviously need to use an
ajax call, and I would call a php file because that has a useful function fgetcsv(), but
can I use this function to enter info into a existing table? I was able to use php to
CREATE a table with this info, but as far as I understand, php has no knowledge of the
DOM... I would have to somehow package the entire column info and have javascript do the
job but I'm a little confused as to how...
Below is a snippet of how I used php to CREATE my table.
$file = fopen("SGS_Fall_Booklist.csv", "r");
$entry= fgetcsv($file);
echo $entry[0] . $_GET["program"] . $entry[1] . $GET["school"] .
$entry[2] . $GET["term"];
echo "<br>AutoFill (last years ISBN's)<br><input id='checkall' type='checkbox' </input>";
echo "<table><tr>
<th>Edit</th>
<th class='coursename'>" . $entry[6] . "</th>
<th class='startdate'>" . $entry[7] . "</th>
<th class='booktitle'>" . $entry[17]. "</th>
<th class='author'>" . $entry[18]. "</th>
<th class='isbn'>" . $entry[16]. "</th>
</tr>";
while(! feof($file))
{
$entry = fgetcsv($file);
echo "<tr>
<td><input type='checkbox'></input></td>
<td class='coursename'>" . $entry[6] . "</td>
<td class='startdate'>" . $entry[7] . "</td>
<td class='booktitle'>" . $entry[17]. "</td>
<td class='author'>" . $entry[18]. "</td>
<td class='isbn'></td>
</tr>";
}
echo "</table>";
fclose($file);
So here's a few things you can do:
(worst) Send the entire table back in the ajax call to PHP, and then let php add your column, and return the updated table (bad plan, lots of unchanged data transferring)
(better) Ajax call to return an entirely new table with your new column (better)
(best) Ajax call to fetch an array or object with your data and then use javascript to iterate over the table and add the data
Pseudo code:
//do your ajax request
foreach(newColumnValues AS key=>value) {
foreach(document.getElementByID("yourtable").elements) {
//If the ordering can change, check the key first, otherwise you could
//just go through every element
if(element[0] == key) {
element[1] = value;
}
}
}
Good luck!
If you have the code above print your ajax response you can then just do this on your javascript:
document.getElementById('container-id-here').innerHTML(your_ajax_response_text);

Categories