Display results from MySQL query into table using PHP - php

This is for a timetable and what it does is displays the previous day's timetable and who has booked each slot (this is for a radio station.)
At the moment it displays who has booked each slot in chronological order however I would like it to say the time next to each result. The query outputs 24 rows (which is from Midnight to 23:00) and next to each slot I would like it to say (00:00, 01:00, 02:00, 03:00... 21:00, 22:00 so on so forth.)
This is my current code:
<?php
include("../config.php");
#// Timetable Clearup Variabls
$yesterday = strtotime('yesterday');
$yesterdow = date('l',$yesterday);
echo "<table width=\"580px\" class=\"board\" border=\>";
$order = "SELECT * FROM timetable WHERE day = '$yesterdow'";
$result = mysql_query($order);
// Error checking
if (!$result) {
// output error, take other action
}
else {
while ($row=mysql_fetch_array($result)){
// Append all results onto an array
$rowset[] = $row;
}
}
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td></tr>";
}
?>
Can you help?

I think we're all looking too hard at a VERY simple problem. You are already using SELECT * in your query, so you're already fetching all three columns from your table. So now, all you need to do is add another cell to each row of your table.
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td><td>" . htmlspecialchars($row['time']) . "</td></tr>";
And to make sure you are fetching your rows in the correct order, you should add an ORDER BY to your query:
SELECT * FROM timetable WHERE day = '$yesterdow' ORDER BY time
If you don't specify an ORDER BY clause, you have no guarantee that you will get the results in any particular order.
And one last thing, you are looping through the rows twice, unnecessarily. Get rid of the foreach loop and put the echo directly inside the while loop.

try this:
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . htmlspecialchars($row['time'])"</td></tr>";

Related

How to use a mysqli result row more than once in PHP?

I am trying to put together a tool to help me with my upcoming fantasy hockey draft while also learning PHP. I am trying to create multiple lists on a page, one that displays the top 10 available players overall and then others that display the top 10 available players by position.
Here is my SQL query/code
include 'db/connect.php';
$sql='SELECT * FROM players WHERE pick IS NULL';
$players=$conn->query($sql);
if($players === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $players->num_rows;
}
Then later in the page I have a while loop that generates a table with the top ten players
while ($row = $players->fetch_array()) {
if ($i == 10) {
break;
}
echo "<tr>";
echo "<td>" . $row['Rank'] . "</td>";
echo "<td>" . $row['Player'] . "</td>";
echo "<td>" . $row['Team'] . "</td>";
...
And all that works fine. However, when I go to use the same method to generate a list containing only a certain position (C, RW/LW, etc...) it starts off where the top 10 player list ends. (See what I mean here: http://i.imgur.com/JApeftU.png)
I assume this has to do with the $players->fetch_array() however I do not know what the best way would be to get around it.
Any ideas?
Thanks!
Populate rows with all the players.
while ($row = $players->fetch_array()) { //→ $rows = $players->fetch_all();
$rows[] = $row;
}
You can use count() to get total amount of players in the array
$totalPlayers = count($rows);
Now you can loop through the array with for loop
for($i = 0; $i < $totalPlayers; $i++){
//echo out the stuff you want
echo $rows[$i]['player'];
}
Or only ten
for($i = 0; $i < 10; $i++){
//echo out the stuff you want
echo $rows[$i]['player'];
}
Well, for the future visitors, lured by the misleading title, the other answer is okay.
While for you personally, the other answer, as well as your question, is wrong.
And it's your idea on using databases is wrong in the first place.
A database is not like a text file, which you but bound to read every time from first line to last. Databases are quite intelligent and intended to return you the very data you requested.
Think it this way: what if your league will grow up to employ thousands of players. It will burden PHP script with lots of useless info, when it needs only a hundred of players.
So, it seems you need different queries to get differen data sets. First, you need a query
SELECT * FROM players WHERE pick IS NULL ORDER BY field DESC LIMIT 10
To get overall top ten, where field is whatever field you're using to determine the "top" player. And then several queries, each getting players for the certain position.
SELECT * FROM players WHERE pick IS NULL AND position=? ORDER BY field DESC LIMIT 10

Array duplicating information

My apologies if this has been addressed - I have been searching all day and haven't found anything that meets my needs.
I have a foreach loop in php that is repeating information ad nauseum, and I am not sure how to fix it. I have tried grouping, array_unique, etc., and haven't found a solution. No row is a true duplicate of another when all variables are taken into account.
I have a table where each line represents a winning ticket. Each line has a unique ID, a date, a tier (1,2,3), and some other variables worth of information. I would like to organize this by date, ascending by tier number, where the date is listed once and each ticket is listed once. Right now, each row is listed as a ticket, but repeats multiple times. Here is my code - I have removed the displays in between as those work fine:
$selectResults = "SELECT * FROM mytable WHERE YEAR(date) = 2014 ORDER BY date DESC, tier ASC";
$getResults = #mysqli_query($connect, $selectResults) or die('query error: ' . mysqli_error($connect));
if(mysqli_num_rows($getResults) == 0){
echo "There are no tickets to display.";
}else{
echo "<table><tr><th>Date</th><th>Tier</th><th>Points</th><th>Prize Amount</th></tr>";
while($row = mysqli_fetch_array($getResults)){
extract($row);
foreach($row as $ticket => $date){
echo "<tr><td>" . date('n/j/Y', strtotime($date)) . "</td><td> </td><td> </td><td> </td></tr>";
if (1 == $tier)
{
(Display Tier 1 tickets for date)
}
if (2 == $tier)
{
(Display Tier 2 tickets for date)
}
if (3 == $tier)
{
(Display Tier 3 tickets for date)
}
}
echo "<tr class='bottomRow'><td colspan='4' /></tr>";
}
echo "</table>";
Get rid of the foreach loop:
foreach ($row as $ticket => $date)
You're already looping over the rows with the while loop. $row just contains a single row, with each column as an element of the array.
Your code should look like:
$last_date = null;
while ($row = mysqli_fetch_assoc($getResults)) {
extract($row);
if ($date != $last_date {
echo "<tr><td>" . date('n/j/Y', strtotime($date)) . "</td><td> </td><td> </td><td> </td></tr>";
$last_date = $date;
}
// Display ticket details
}

php, sort an array from mysql

I'm running a query on three columns; one column contains text, the other two contain numbers. I do a calculation on these numbers to get a new number called $average. I then spit out the result to an html table. The rows in the table are sorted in the order they come out of the database. I'm trying to sort the table so that the data is displayed from highest $average to lowest (while still be correctly associated with the correct text value from the first column).
I've tried some asort and foreach stuff, but I've only succeeded in making a mess of errors.
Any ideas as how I go about this?
Thanks.
This is the current state of play:
/ db query
if (!$result = mysqli_query($link,"SELECT quiz_name,
quiz_attempts,
cumulative_score
FROM scoredata")) {
echo("There was a problem: " . mysqli_error($link));
exit();
}
...
// got results?
if(mysqli_num_rows($result) >= 1) {
$output = "";
$output .= "<table>\n";
$output .= "<tr><th>Quiz name</th> <th>Played</th> <th>Avg. score</th></tr>\n";
while($row = mysqli_fetch_array($result)) {
$output .= "<tr><td>".str_replace('_', ' ', $row['quiz_name']) . "</td>";
$output .= "<td>" . $row['quiz_attempts'] . "</td>";
// calculate average score
$average = $row['cumulative_score']/$row['quiz_attempts'];
$output .= "<td>" . round($average,2) . "</td></tr>";
}
$output .= "</table>\n";
echo $output;
}
...
You can do calculation and sorting in your query:
SELECT
quiz_name,
quiz_attempts,
cumulative_score,
(cumulative_score/quiz_attempts) as score_avg
FROM scoredata
ORDER BY score_avg DESC
You can
let the db do the sorting (as suggested by other posters)
sort the data yourself (as you are trying to do)
let the user sort the data via JavaScript functions. My favourite is
http://www.javascripttoolbox.com/lib/table/
Make this your query
SELECT quiz_name,
quiz_attempts,
cumulative_score,
cumulative_score / quiz_attempts as avg_score
FROM scoredata
ORDER BY avg_score

Printing data horizontally using php and mysql

I want to print data from the database in a horizontal manner.
I have two table one that holds products names and another that holds products performance by months eg i want data to appear in a table like this
product name,performance by months from january to december
eg
product A,1000 ,2000, etc performance by months
product B,2000,3300, etc performace by months
Edit: I didn't realize you said you have two tables. So the query in my solution should be adapted with a JOIN and ordered, but we cannot dig further into this without knowing your schema. My solution addresses the main concern (i.e. printing results horizontally), provided you obtain two fields to show in two different rows.
Just retrieve your data and store it in a multidimensional array, THEN create the table.
$data = array();
$sql = "SELECT product, performance FROM table";
$rs = mysql_query($sql);
while ($row = mysql_fetch_assoc($rs))
{
$data[] = array($row['product'], $row['performance']);
}
echo "<table><tr>";
// print products in the first line of the table
foreach($data as $d)
{
echo "<td>" . $d[0] . "</td>";
}
echo "</tr><tr>";
// then print performances
foreach($data as $d)
{
echo "<td>" . $d[1] . "</td>";
}
echo "</tr></table>";

Row won't increase in do-while loop

I'm having some problems with the php script below that I'm currently working on. What I am trying to do is make a list with 5 events that are being shown ordered by date.
In my database I have a table with events. Each event has a date (DATETIME), an id and a name. What the php needs to do is check the table with events and filter the ones that have already passed. If an event has already passed, it's not shown. If it still has to happen, it's shown.
Now the problem is that in the do while loop, the script doesn't seem to go to a next row when it has had a run.
For example: if the database table has 10 events in it, it will show 10 times the event that's on the first row of the table when testing.
I need to know what I'm doing wrong, or if there is a way to make the row increase after each run of the loop.
<?php
$test_query_kalender = "SELECT * FROM kalender ORDER BY datum ASC";
$test_result_kalender = mysql_query($test_query_kalender);
$rij_kalender = mysql_fetch_assoc($test_result_kalender);
$vandaag_unix = time();
$datum_unix = strtotime($rij_kalender['datum']);
$i = 0; //this variable is used to insure that only 5 items are being shown on the page
do{
if($datum_unix >= $vandaag_unix) //checks if the date of the event has already passed
{
//if the date has not passed, the event will be shown
echo "<p>" . date("d-m-Y", $datum_unix) . " " . $rij_kalender['naam'] . "</p>";
$i++;
}
else
{ //if it has already passed then it should put nothing, but for testing I put a line in it
echo "<p>" . $rij_kalender['naam'] . "</p>";
}
} while(($i <= 4) && ($rij_kalender = mysql_fetch_assoc($test_result_kalender)));
echo "<p>While loop finished</p>"; //just some checking
?>
Your code loads the date once and then compares it to today each time. Move
$datum_unix = strtotime($rij_kalender['datum']);
into the loop, before the date check.
Try this:
<?php
$test_query_kalender = "SELECT * FROM kalender ORDER BY datum ASC";
$test_result_kalender = mysql_query($test_query_kalender);
$rij_kalender = mysql_fetch_assoc($test_result_kalender);
$vandaag_unix = time();
$datum_unix = strtotime($rij_kalender['datum']);
$i = 0; //this variable is used to insure that only 5 items are being shown on the page
while($rij_kalender = mysql_fetch_assoc($test_result_kalender))
{
$datum_unix = strtotime($rij_kalender['datum']);
if($datum_unix >= $vandaag_unix) //checks if the date of the event has already passed
{
//if the date has not passed, the event will be shown
echo "<p>" . date("d-m-Y", $datum_unix) . " " . $rij_kalender['naam'] . "</p>";
$i++;
}
else
{
//if it has already passed then it should put nothing, but for testing I put a line in it
echo "<p>" . $rij_kalender['naam'] . "</p>";
}
if ($i == 5) break;
}
echo "<p>While loop finished</p>"; //just some checking
?>

Categories