Variation on a cross tab/pivot table - php

I've been doing a lot of basic stuff with PHP, but have come up with a new twist on how I want to display some tabular data. I looked at the basic rules for constructing pivot/cross tab displays, but what I'm looking for seems to be a bit different. The primary data is stored in 1 table as (along with other fields):
the station
ID of ambulance at that station
current status of ambulance (available, unavailable, out of service)
My present code outputs this...but looking for this:
http://www.countryhicksystems.com/upload/stack.jpg
I know we're to use PDO or MySQLi, but I set this up as a quick prototype.
//Log in, etc. code before this
$query = "SELECT * FROM $usertable WHERE $ems = $editID
Order by equip_station, equip_descrp";
$result = mysql_query($query);
if($result)
{
echo "<table width=\"90%\" border='1' align=\"left\" height=\"Auto\" cellpadding=\"3\" cellspacing=\"3\">
<tr>
<th width=\"65\"><div align=\"center\">Station</div></th>
<th >Status</th>
<th >As of Date</th>
<th >Description</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td class=\"columnfont\">" .$row["$name"]."</div></td>";
if ($row['equip_status'] == 'Available')
{
echo "<td class=\"green\">" .$row["$id"]."</div></td>";
}
elseif ($row['equip_status'] == 'Unavailable')
{
echo "<td class=\"red\">" .$row["$id"]."</div></td>";
}
else
{
echo "<td class=\"black\">" .$row["$id"]."</div></td>";
}
echo "<td class=\"cellfont\">" .$row["$availdate"]."</div></td>";
echo "<td class=\"cellfont\">" .$row["$descr"]."</div></td>";
echo "</tr>";
}
}
?>
</p>
</div>
How would I change my present code to display Station Ambulances across a row instead of down a column?
Thanks in advance everyone.

Related

Get person name first and retrieve external data with COUNT based on this name

I'm making a sports solution to retrieve data from play by play to webpage.
And now I am stuck with a moment to retrieve player name from mysql db, put to boxscore table (that was done), and then retrieve all stats based on this name.
As example - how many points he made, how many assists were associated with his name, etc.
At the end I want to get this kind of table (all formating /styling done and ready):
Here is a php code, question based in the "echo" point.
I cant finnd proper way to count how many assists a.e. player made in the same request.
<?php
require "connection.php";
$game_id = 1760;
$player = 'KURBANOV, NIKITA';
$team = 'CSKA Moscow';
$stmt = $pdo->prepare('SELECT * FROM game_results WHERE game_id = :game_id AND team = :team AND action = "Assist" ORDER BY player DESC');
$stmt->execute(array('game_id' => $game_id, 'team' => $team ));
$result = $stmt -> fetchAll();
echo '<table class="table table-condensed table-hover"><tbody>';
echo '<thead>
<tr>
<th>Name</th>
<th>POS</th>
<th>MIN</th>
<th>PTS</th>
<th>OREB</th>
<th>DREB</th>
<th>TREB</th>
<th>AST</th>
<th>STL</th>
<th>TOV</th>
<th>Fm</th>
<th>Fc</th>
</tr>
</thead>';
foreach( $result as $row ) {
echo '<tr>';
echo '<td>'.$row['player'].'</td>';
echo '<td>'.$row['action'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '</tr>';
}
echo '</tbody></table>';
Here is the db data example:
DB example
Ok after your edit I think I guessed what you want to do.
You want to count how many entrys you have in your table of a specific player and a specific action.
SELECT player,
Count(CASE action
WHEN 'Assist' THEN 1
ELSE 0
end) AS assists,
Count(CASE action
WHEN '<other case>' THEN 1
ELSE 0
end) AS other_case
FROM `game_results`
WHERE 1
GROUP BY player
This above SQL Select should do what you want, replace other case with what ever you else have.
EDIT:
You should be able to print it out just like you did before:
<?php
// your other code ...
echo '<table class="table table-condensed table-hover"><tbody>';
echo '<thead>
<tr>
<th>Name</th>
<th>assists</th>
<th>other case</th>
</tr>
</thead>';
foreach( $result as $row ) {
echo '<tr>';
echo '<td>'.$row['player'].'</td>';
echo '<td>'.$row['assits'].'</td>';
echo '<td>'.$row['other_case'].'</td>';
echo '</tr>';
}
echo '</tbody></table>';

How could you use PHP and a SQL database to change HTML <h> content?

I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}

Looping SQL Results into a table

I'm just struggling to have my SQL output loop within a table. Currently, it displays one result within the table and the remaining out of it.
If I put the entire table within the while loop, it creates a new table for each row...
Please help!
Code below
if (mysqli_num_rows($result) > 0)
{
echo
"<table class='xsmall' align='center'>
<tr><th>Costume ID</th>
<th>Description</th>
<th>Size</th></tr>";
while($row = mysqli_fetch_array($result))
{
//-----------------Echoing Results-----------------------//
echo
"<tr><td>".$row['Fname']."</td>
<td>".$row['Sname']."</td>
<td>".$row['AvgSpend']."</td></tr>
</table><br>";
}
}
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "
<tr>
<td>'".$row['Fname']."'</td>
<td>'".$row['Sname']."'</td>
<td>'".$row['AvgSpend']."'</td>
</tr>";
}
echo "</table>";

Search the results from a query

I have a site where members can mark other members as 'a favourite'. User are able to search the members table in various ways and I want to show from any of the results that are returned whether or not the users returned are favourites of the current user.
This is some very simplified code I have been using to try and get this query to work but I just can't figure it out. Whenever I add 'GROUP BY' to avoid duplicate results from my LEFT JOIN the 'if' statement does not work. The 'if' statment does work however, if I omit the 'GROUP BY' but I get all rows from members table and the favourites table. Thanks.
$result = mysqli_query($db_conx, "SELECT members.*, user_favourites.* FROM members LEFT JOIN user_favourites ON members.id = user_favourites.fav_id GROUP BY members.id");
echo "<table border=''>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>A favourite of User</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
if ($visitor == $userid ){
$msgs = "x";
}
else { $msgs = "0";
}
echo "<td>". $msgs. "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I suggest to you, tu use 2 query's insted one. Simple query is a fast querys. If your site scale up, your query will be slow query and it cause performance problems.
Idea:
For one hand: SELECT FROM members, get all and put it inside array, key=member.id
$members[$row['member_id']]=$row;
On the other hand: SELECT * FROM user_favourites, and put it inside the previous array, refereced by the key fav_id use distinc if you have duplicates.
$members[$row['fav_id']]['favourites']=$row;
Perfect now you have all you need, an array with all information, iterate it.
JilianJ something like this:
<?
//Prepare
$all_users=array()
$query_users='SELECT * from user';
$query_favourites='SELECT * FROM user_favourites';
//Now I find all members information
$users=mysqli_query($db_conx,$query_users);
while($user = mysqli_fetch_array($users)) {
$all_users[$user['id']]=$user;
}
//Now I add favourite information to the users information
$favourites=mysqli_query($db_conx,$query_favourites);
while($favourite = mysqli_fetch_array($favourites)) {
$all_users[$favourite['fav_id']]['fovourite'][]=$favourite['fav_id'];
}
?>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>A favourite of User</th>
</tr>
<? foreach ($information as $key=>$item) {?>
<tr>
<td><?=$item['firstname'];?></td>
<td><?=$row['lname'];?></td>
<td><?=$row['email'];?></td>
<td>
<? foreach($item['favourites'] as $key2=>$item2) { ?>
<p><?=$all_members[$item2]['name];?></p>
<? } ?>
</td>
</tr>
<? } ?>
</table>
Good luck

How to sort data tables using the header row by alphabetical order

Im doing a sch project and I need help in sorting my data table in alphabetical order by clicking the header row. Im using MySQL and I intend to use a php to implement it. Can anyone help me? Thanks.
This is my code:
This is a php file.
<?php
# $db = new mysqli('localhost', 'f33s01', 'f33s01', 'f33s01');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select * from gyms";
$result = $db->query($query);
$num_results = $result->num_rows;
echo "<table border=\"3\" cellpadding=\"5\" class=\"dirtable\" style=\"margin-bottom:15px\">
<tr align=\"center\" class=\"gold\">
<th>Number</th>
<th>Gym Name</th>
<th>Address</th>
<th>Location</th>
<th width=\"18%\">Operating Hours</th>
<th>Reservation</th>
</tr>";
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo "<tr>";
echo "<td align=\"center\">".($i+1)."</td>";
echo "<td align=\"center\">".stripslashes($row['gymname'])."</td>";
echo "<td>".stripslashes($row['address'])."</td>";
echo "<td>".stripslashes($row['location'])."</td>";
echo "<td align=\"center\">".stripslashes($row['operatinghours'])."</td>";
echo "<td align=\"center\"><input type= \"submit\" value=\"BOOK NOW\" class=\"bookbutton\"></td>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
$result->free();
$db->close();
?>
To strictly answer your question, you can use links in the column headings to pass $_GET variables to your page, and customize your mysql queries with SORT BY in order to render the data. I'll give a rough outline, this should get you pointed in the right direction. You will need to add in more logic on the heading urls to enable sorting in multiple directions.
For the heading:
echo "<th><a href='".$_SERVER[REQUEST_URI]."?orderby=gymname&order=desc'>Gym Name</a>";
And then before your mysql code, have a switch statement
switch($_GET[orderby]) {
case "gymname":
$filter_orderby = "gymname";
break;
case "address":
$filter_orderby = "address";
break;
//...other cases...
}
switch($_GET[order]) {
case "desc":
$filter_order = "DESC";
break;
case "asc":
$filter_order = "ASC";
break;
}
Now, you can append those to your query:
$myquery = "SELECT * FROM gyms WHERE 1 = 1";
if(isset($filter_orderby) {
$myquery .= " ORDER BY ".$filter_orderby." ".$filter_order;
}
//Result: SELECT * FROM gyms WHERE 1 = 1 ORDER BY gymname DESC
If this data is not paginated or otherwise in a non-flat presentation then I would agree with Nikita Singh's suggestion of using a jQuery plugin - another is http://tablesorter.com/

Categories