php while loop echoing element outside of looped content - php

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>

Related

How to display a button for each row in a table

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']".

MySQL and PHP - make href remember previous variable

I am quite new to PHP, but come with some knowledge of JavaScript.
I am trying to construct a MySQL table which has sortable columns by header, which I managed figure out through looking around the web, etc; but then wanted the SQL query to use a WHERE clause which only shows rows that meet that clause (and it works), but the problem is that when I then sort the columns it goes back to the original value of the $catergory variable.
I hope that makes sense.
Could somebody please tell me what I am doing wrong and either if I need to change the SQL query or find a way to get the PHP to remember the reassigned value of $catergory, when I want to sort the columns afterwards?
Here is my code:
<?php
// Create connection
$con = mysqli_connect("host","user","password","database") or die("Some error occurred during connection " . mysqli_error($con));
$categoryFilter = array('boardroom', 'staffroom', 'kitchen');
$category = 'boardroom';
if (isset($_GET['categoryFilter']) && in_array($_GET['categoryFilter'], $categoryFilter)) {
$category = $_GET['categoryFilter'];
}
$orderBy = array('Image', 'Description', 'Light', 'Room');
$order = 'Image';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}
?>
<div class="catbuttons">
<ul>
<li>Boardroom</li>
<li style="height: 17px">Staffroom</li>
<li>Kitchen</li>
</ul>
</div>
<div class="index">
<table border='1'>
<tr>
<th>Image</th>
<th>Description</th>
<th>Light</th>
<th>Room</th>
</tr>
<?php
$result = mysqli_query($con,"SELECT * FROM officeindex WHERE Room='".$category."' ORDER BY ".$order)
or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" , $row['Image'] , "</td>";
echo "<td>" , $row['Description'] , "</td>";
echo "<td><img src='" , $row['Light'] , "'></td>";
echo "<td>" , $row['Room'] , "</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT:
Thank you everyone, I have implemented your suggested solutions to my original question and changed the code above, but I am now having further difficulty. The purpose of my code is to construct an interactive product list of sorts. Now that I have the categories (thanks for pointing out the spelling mistake) working, I want the table, at first, to show all the categories, i.e. all the products in the list, before the user clicks on a specific category.
The other problem is that I can't work out what to do about cells which contain multiple categories (Some products fall into multiple categories).
I've thought about using arrays or loops or booleans or some kind to do both of the above, but my knowledge is limited to JavaScript and I'm a bit lost in PHP, even though there are similarities. Please forgive my ignorance.
I hope I have explained this clearly
Could anyone help me please?
The links in your tableheader only contain the orderBy parameter. If you want to keep the categoryFilter, you need to include it in the href of your headers.
For example:
<tr>
<th>Image</th>
<th>Description</th>
<th>Light</th>
<th>Room</th>
</tr>
For the category filter it's the other way around of course:
<li>Boardroom</li>
<li>Staffroom</li>
<li>Kitchen</li>
Also, as #K.K.Smith pointed out, you might want to replace catergory with category
In your links, You have to put the varaibles if they exists.
Example :
<a href="?categoryFilter=staffroom<?php if isset($_GET['orderBy'] echo '&orderBy=", $_GET['orderBy'];?>" />

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>

Extracting URL's from mysql database and setting as single word clickable link

I would like to extract URL's from a mysql database. However I wish to link the URL to a single word 'CLICK' in a table.
The snippet of code below extracts data from a mysql database and puts it in a table as a series of rows. For each row there is a respective URL which I also wish to extract from the database. Instead of showing the full and long URL I just want to have the word CLICK against each row which people can then click to access that URL. Can any body tell me how that is done?
$q="SELECT * FROM railstp WHERE DOWNLOAD='$changeday'";
$r=mysqli_query($mysql_link,$q);
if ($r)
{
echo "<strong>Network Rail Schedule (STP) updates downloaded: $changeday</strong>";
echo "<p> </p>";
echo "<Table id='customers'>
<tr>
<th>Headcode</th>
<th>Traction</th>
<th>From</th>
<th>To</th>
<th>Departing</th>
<th>Destination</th>
<th>Depart</th>
<th>Arrive</th>
<th>ATOC</th>
<th>Runs</th>
<th>Load</th>
<th>Speed</th>
</tr>";
while ($row=mysqli_fetch_array($r,MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>".$row['HEADCODE']."</td>";
echo "<td>".$row['TRACTION']."</td>";
echo "<td>".$row['STARTDATE']."</td>";
echo "<td>".$row['ENDDATE']."</td>";
echo "<td>".$row['DEPART']."</td>";
echo "<td>".$row['ARRIVE']."</td>";
echo "<td>".$row['DEPARTTIME']."</td>";
echo "<td>".$row['ARRIVALTIME']."</td>";
echo "<td>".$row['ATOC']."</td>";
echo "<td>".$row['RUNS']."</td>";
echo "<td>".$row['LOAD']."</td>";
echo "<td>".$row['SPEED']."</td>";
echo "</tr>";
}
echo "</Table>";
}
else {echo '<p>'.mysqli_error($mysql_link).'</p>' ;}
}
show_records($mysql_link);
mysqli_close($mysql_link);
In its simplest form:
CLICK
Add this to your row code:
echo "<td><a href='".$row['URL']."'>CLICK</a></td>";
What this does is add the URL as the parameter to the link but as the link text only show CLICK. Replace URL with the column name for your url.

How to submit parameters by hyperlink-url and retrieve them in php?

Carrying values in a while cycle, each value is extracted from a SQL table, and I need to carry em in a since I'm making a list of items purchased from a specific client. I'm using this line for the href url:
echo "<table width=1200 style align=left>";
while($row3 = mysqli_fetch_array($rs3)){
$space = array("");
$text=$row3['description'];
$dash="_";
$url = preg_replace("![^a-z0-9]+!i", "_", $text);
$url= "".$url.".php";
echo "<tr><td colspan=2 style align=center><span class=font>" . $row3['relid'] . "</span></td><td width=132 style align=center><span class=font>" . $row3['invoiceid'] . "</span></td><td width=400 style align=center <span class=font><a href=$url>" . $row3['description'] . "</span></A></td><td width=132 style align=right><span class=font>" . $row3['amount'] . "</span></td><td width=132 style align=center><span class=font>Pendiente</span></td><td width=132 style align=left><span class=font>" . $row3['duedate'] . "</span></td></tr>";
}
mysqli_close($con3);
echo "</table>";
echo"<table width=1200>";
echo " <tr class=font>
<td width=1200 height=22 colspan=7 background=border-green-horizontal.png> </td>
";
I'm generating the url from the Description I extract from the database but I need to carry the Order ID, Client ID, etc from the specific row.
Each variable is needs to be carried to a form where the user will fill some fields regarding the product the client bought (Medical Test Results), and I need those variables to mark as "Done" so It won't show up again on the list.
Fix these syntax errors, report back if still broken.
<td width=400 style align=center <span class=font><a href=$url>" . $row3['description'] . "</span></a></td>
-->
"<td width=400 style align='center'><span class='font'><a href='$url'>" . $row3['description'] . "</span></a></td>"
EDIT:
Do you mean how to append a var to an url, so it can be retrived on the called page?
You can append the var to the url by echo "<a href='{$url}?id={$var}'>.
On the called page, you can read it by $_GET['id']

Categories