MySQL and PHP - make href remember previous variable - php

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'];?>" />

Related

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>

Create multiple tables by cycling through a query

Here is my current code:
$varVeh=$_POST['Veh_num'];
$sql_HiScores = "SELECT
c.course_name as course,
e.distance as distance, e.score as score,
e.time as time, e.user as User
FROM hc_entries e
LEFT JOIN hc_course c on e.course=c.course_num
WHERE e.vehicle=$varVeh
ORDER BY course, score DESC";
$result_HiScores = mysql_query($sql_HiScores);
$sql_vehName="SELECT Veh_name FROM hc_vehicle_type WHERE Veh_num=$varVeh ";
$result_vehName = mysql_query($sql_vehName);
$vehName=mysql_fetch_assoc($result_vehName);
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th></tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result_HiScores))
{
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
}
echo "</table>";
What I think I have to do is create a query that selects * from e.course that builds an array. Then cycle through the existing query with the array results. Finally, I would like to display individual tables for each course and limit it to the top 5 results for each course.
Can anyone confirm or deny my logic, and point me in a direction?
First of all, you shouldn't be using the mysql_ functions, they're deprecated. At the least, you should switch to mysqli_ (a pretty easy switch), or better, learn how to use PDO. It's a bit different and more involved to switch, but your code will be better and safer for it.
With that out of the way: your logic is pretty accurate. Limiting your results to the top 5 results for each course in one query isn't something that's easily done with SQL to my knowledge, so your plan is good: query a list of courses, then cycle through them with your existing query, running it once for each course, with a LIMIT 5 to get the top 5.
You might as well keep the table generation within this loop as well, since it's a table-per-course. You'd want to move the VehName query out of the loop, since you only need to run that once.
Also, some unsolicited PHP advice: any text outside of the tags will just be output directly, so take advantage of its built-in-templating and alternative syntax to make your table generation code nicer:
<?php
/* Gather your data here... */
?>
<table>
<tr><th>Best Scores for <?php echo $vehName['Veh_name'] ?></th></tr>
</table>
<table border='1'>
<tr>
<th>Course</th>
<th>Score</th>
<th>Distance</th>
<th>Player</th>
<th>Time</th>
</tr>
<?php while($row = mysql_fetch_array($result_HiScores)): ?>
<tr>
<td><?php echo $row['course'] ?></td>
<td><?php echo $row['score'] ?></td>";
<td><?php echo $row['distance'] ?></td>";
<td><?php echo $row['User'] ?></td>";
</tr>
<?php endwhile; ?>
</table>
put the entire table html inside the while loop and add 'LIMIT 5' to the end of your query

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>

Using an incremented value in a SELECT WHERE query MYSQL

Let me start off that I have only been coding for the past few months. I know I've probably got a ton of mistakes or bad practices everywhere. I like constructive criticism, so please let me know what i can do better, along with how to address my current issue.
This code's purpose is to create a table of part numbers, and their associated location column data (storage type, Rack number, Shelf number) based on previously entered information. I've got the entry form working perfectly. I type in a number of parts I want to search for, and it posts that number back to itself. I'm then presented with that number of text input fields to put in part numbers.
//this form is to submit the number of parts you're looking for,
//and posts back to itself
<form action=View2.php method="post">
<input type="text" name="num">
<button type="submit">Number of Parts</button>
</form>
//This form takes the posted number, and creates that many text fields,
//populated with the number part you are entering.
<form action="List.php" method="post">
<?php while ($i<=$num){
echo "<input type='text' name='part$i' value='part$i'><br><br>";$i++;}?><input type="hidden" name="num" value="<?php $num?>">
<button type="submit">Submit</button>
</form>
My problem comes with running a mysqli_query to populate the table. I'm stuck as to where to go from here. I know that i need to take each part number that gets posted, and use it as the criteria in a SELECT WHERE search, so i made this While loop:
<?php
echo "<table border='1'>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Rack</th>
<th>Shelf</th>
</tr>";
while($i<=$num){
$x=$_POST["part$i"];
$result = ($con,"SELECT * FROM parts WHERE pn ='$x'");
$row = ($result);
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['rcb'] . "</td>";
echo "<td>" . $row['ra'] . "</td>";
echo "<td>" . $row['sh'] . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";?>
The page crashes at this point, but if i comment out the $result line, i'll get the table with the part number fields populated with the values from the previous page.
Anyone have any idea what i'm doing wrong, or how i can do it better?
This line doesn't do anything good :
$result = ($con,"SELECT * FROM parts WHERE pn ='$x'");
You need to actually query the DB.
$mysqli = new mysqli("localhost", "my_user", "my_password", "...");
...
$result = $mysqli->query("SELECT * FROM parts WHERE pn ='$x'");
You should use prepared statements so your code isn't open to sql injections though...

Can't delete a user from database by clicking delete button on the same page

I searched fot the solution but nothing works.
<?php
$result = mysql_query("SELECT username, EmailAddress FROM users", $connection);
echo "<form method='post'><table class='mecz' cellpadding='0' cellspacing='0' border='0'>
<tr>
<th>user names:</th>
<th>address e-mail</th>
<th></th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr align='center'>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['EmailAddress'] . "</td>";
echo "<td><input class='delete' type='submit' name='delete' value='usuĊ„' /></td>";
echo "</tr>";
}
echo "</table></form>";
//here a part when i'm trying to pass delete action from the form
?>
<?php
if (($_POST['username'] != "") && (isset($_POST['delete'])))
{
$username = $_POST['username'];
$query = "DELETE FROM users WHERE username = '".$username."' AND '".$_POST['delete']."'";
$result = mysql_query($query,$connection);
echo mysql_error();
}
?>
I think the solution is not very complex but i can't find it, please help.
Thanks,
Kris
you aren't sending username in the code you posted, so $_POST['username'] isn't set and thus the delete isn't executed.
even if you would enter the if-block, your delete-query doesn't make much sense - what should AND '".$_POST['delete']."' do? that part seems pretty sensless.
you try to make one form containing several submit-buttons (one for every user). on server-side you can't determine wich submit-button is pressed as the whole form gets sent as one big bunch of data. you'll need one form per user or simply use links (a-elements) to sent the delete- and username-values (but note that in the latter case you'd do GET instead of POST-requests)
you don't specify a action for your form - this might or might not be a problem in your case, please see the various comments to your question about this for more information.
your delete-query is perfectly open for sql-injections. please consider using prepared statements or at least mysql_real_escape_sting to avoid this.
and this are only the real problematic points that prevent your code from working at all or leave awkward security-holes. in addition, there are some things that are just unneccessary or some kind of messy (like calling mysql_error every time instead of doing that only if a query fails - but maybe you just added that for debugging).
altogether it seems like you should start reading a good book or some detailed tutoriala again to refresh and extend your fundamental understanding of php/mysql/html.

Categories