sorting row data in table PHP? - php

i have a table being echo'd from a single query to a table in our database and i get it to echo out the following table;
http://www.skulldogs.com/dev/testview.php
i want it to sort the "yellow" rows under the correct green rows where the "mainToon" name matches for example:
high voltege
--REAL MCCOY
--Cpt Hook
riazall
-- Valeside
my code to echo the above page is;
<?php
$result = mysql_query("SELECT * FROM `members`");
echo "<table border='1'>
<tr>
<th>Character ID</th>
<th>Name</th>
<th>MainToon</th>
<th>toonCategory</th>
</tr>";
while ($row = mysql_fetch_array($result)) {
$characterID = $row['characterID'];
$name = $row['name'];
$startDateTime = $row['startDateTime'];
$logonDateTime = $row['logonDateTime'];
$logoffDateTime = $row['logoffDateTime'];
$location = $row['location'];
$role = $row['role'];
$vouchedBy = $row['vouchedBy'];
$positionHeld = $row['positionHeld'];
$remarks = $row['remarks'];
$afkNotice = $row['afkNotice'];
$toonCategory = $row['toonCategory'];
$mainToon = $row['mainToon'];
$watch = $row['watch'];
if ($toonCategory == 'Main Toon') {
echo "<tr bgcolor='#00FF00'>"; }
else {
echo "<tr bgcolor='#FFFF00'>"; }
echo "<td>" . $characterID . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $mainToon . "</td>";
echo "<td>" . $toonCategory . "</td>";
echo "</tr>";
}
echo "</table>";
?>
at the moment i am not echo the other data until i can figure out how to display this table accordingly. can it be done this way?
this is how i want to display the table;
http://www.skulldogs.com/dev/mockup.php

Add an ORDER BY clause to your sql:
SELECT * FROM `members` ORDER BY toonCategory;
If there are other values above and below "Main Toon", You can order by a boolean:
SELECT * FROM `members` ORDER BY toonCategory = 'Main Toon' DESC;
EDIT:
Now I see what you are after as you have put up the example, try:
SELECT * FROM `members` ORDER BY CONCAT(MainToon, Name);
if the blank spaces are empty strings or:
SELECT * FROM `members` ORDER BY COALESCE(MainToon, Name) DESC, Name;
if the blank rows are null.

Try SELECT * FROM members ORDER BY toonCategory;

Related

How do i loop through but replace missing data with blanks in table

I am trying to display a table to show all the subjects the first student takes, then all the progress grades the student has made in that subject.
However, a student may not have a grade in a certain column so i need to place a blank or 'no grade' in place of it.
Instead i get them stacked side by side...
As you can see below '7(Pc3)' in English should be in the 'PC3' column and 'PC2' should say no grade or blank.... If possible -
Thanks
I have the loop working to fetch the students, plus the loop working to fetch all the subjects for that student.
And can display all the grades - but they don't line up with the right column
while ($res = $result->fetch_assoc()) {
echo "<tr><td>" . $res['subname'] . "</td>";
$result2 = mysqli_query($mysqli, "SELECT *
FROM grades
JOIN gradesets ON grades.gradeset_id = gradesets.id
WHERE grades.student_id = {$row['id']}
AND grades.subject_id = {$res['id']}
ORDER BY grades.gradeset_id ") or die($mysqli->error);
while ($res2 = $result2->fetch_assoc()) {
echo "<td>" . $res2['grade'] . "</td>";
//echo "<td>" . $res2['gradeset_id'] . "</td>";
//print_r($res2);
$resset = $res2['gradeset'];
$resset2 = substr($resset, -1);
//print_r($resset);
//print_r($resset2);
}
}
So i can echo out the right grades, but need to test they match up in the right columns... Here is the full code if needed...
$student = $mysqli->query("SELECT * FROM student");
echo "<center>";
echo "<h2>Data Wall</h2>";
echo "<h3>PHP</h3>";
echo "<hr/>";
while ($row = $student->fetch_assoc()) {
echo "<table border='1'>
<tr>
<th>ID</th>
<th>STUDENT</th>
<th>HOUSE</th>
</tr><br>";
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['stuname'] . "</td>";
echo "<td>" . $row['house'] . "</td>";
echo "</tr><br><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>";
echo "<tr><th>SUBJECTS</th><th>PC1</th><th>PC2</th><th>PC3</th><th>PC4</th></tr>";
$result = mysqli_query($mysqli, "SELECT subjects.id,subjects.subname
FROM student
JOIN grades ON student.id = grades.student_id
JOIN subjects ON subjects.id = grades.subject_id
WHERE student.id = {$row['id']}
GROUP BY subjects.subname ORDER BY subjects.id ") or die($mysqli->error);
while ($res = $result->fetch_assoc()) {
echo "<tr><td>" . $res['subname'] . "</td>";
$result2 = mysqli_query($mysqli, "SELECT *
FROM grades
JOIN gradesets ON grades.gradeset_id = gradesets.id
WHERE grades.student_id = {$row['id']}
AND grades.subject_id = {$res['id']}
ORDER BY grades.gradeset_id ") or die($mysqli->error);
while ($res2 = $result2->fetch_assoc()) {
echo "<td>" . $res2['grade'] . "</td>";
//echo "<td>" . $res2['gradeset_id'] . "</td>";
//print_r($res2);
$resset = $res2['gradeset'];
$resset2 = substr($resset, -1);
//print_r($resset);
//print_r($resset2);
}
}
}
echo "</tr>";
echo "</table>";
echo "</center>";
$mysqli->close();
?>
Since PHP 5.3 you can use Elvis operator - ?:
And since PHP 7 you are able to use Null Coalescing Operator - ??
Either of these you can use to display some other information if you row is empty. For example (PHP 7+):
echo "<td>" . ($res2['grade'] ?? 'No grade') . "</td>";
Would result to either a grade, or No grade text if string is empty or false.
Hope this helps!
In your inner query, you're doing an INNER JOIN, which selects only those rows that have a match in the gradeset table. It looks like you want a LEFT OUTER JOIN, so that you get null placeholders where there is no match:
SELECT *
FROM grades
LEFT JOIN gradesets ON grades.gradeset_id = gradesets.id
WHERE grades.student_id = {$row['id']}
AND grades.subject_id = {$res['id']}
ORDER BY grades.gradeset_id
This way, in your query result, instead of getting:
4 (PC1)
7 (PC3)
6 (PC4)
You'll get:
4 (PC1)
null
7 (PC3)
6 (PC4)
You could build an array of empty grades and then replace them with any data from the query. Like so:
$grades = [1 => '', 2 => '', 3 => '', 4 => ''];
while ($res2 = $result2->fetch_assoc()) {
$grades[$res2['gradeset']] = $res2['grade'];
}
foreach ($grades as $grade) {
echo "<td>" . $grade . "</td>";
}

Trouble with Queries and JOINS

The main page I am using is called the Project Details Page which when you select a project number on the form will query the subform for any records pertaining to that project number and display them in this page named the (TasksSubform).
This page called (TasksSubform) uses a php file called mysqli_connect.php to obtain a database connection and assigns that connection to $dbc in the mysqli_connect.php file.
This page then query’s table 1 named 'CommonTasks', and starts displaying the data row by row in a table on the page using
while($row = $result->fetch_assoc())
Currently one of the columns in the record being displayed is named “AssignedTo” which produces the unique ID number in the Employees table instead of the text value of the employees name associated with the ID number. So, I need to be able to list the records in the CommonTasks Table using Fetch then, when it tries to display the value in the “AssignedTo” column within the Common Tasks Table, it must lookup the ID in the Employees table which equals the same value in the Common Tasks Table, and replace the number value of the Assigned To Field with the text value in the Employees table.
COMMONTASKS
EMPLOYEES
* Add
* AssignedTo
* Attachments
* Cost
* CostInDays
* Description
* DueDate
* EmployeeID
* ID
* PercentComplete
* Priority
* StartDate
* SubmissionDate
* Title * ID
* Address
* BusinessPhone
* City
* Company
* CountryRegion
* EmailAddress
* FaxNumber
* FirstName
* HomePhone
* JobTitle
* LastName
* MobilePhone
* Notes
* StateProvince
* WebPage
* ZIPPostal Code
This is what I have. Yet, all it is producing is a blank in the Assigned To field on the php page.
enter image description here
I am a novice to php and mysql.
This is probably something simple which I am overlooking.
Yet, I have been troubleshooting various methods for the past few days, and just cant seem to figure out what I am doing wrong.
<?php
// Get a connection for the database
require_once('../mysqli_connect.php');
// Create a query for the database
$sql = "SELECT * FROM `CommonTasks`";
$employee = "SELECT ID, LastName, LastName FROM Employees JOIN CommonTasks ON Employees.ID=CommonTasks.AssignedTo";
$emp = "SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = CommonTasks.AssignedTo LIMIT 1";
$emp1 = "SELECT id as LastName, FirstName FROM Employees WHERE ID = CommonTasks.AssignedTo LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$result1 = #mysqli_query($dbc, $sql);
$result2 = #mysqli_query($dbc, $emp);
$result = $dbc->query($sql);
$link = "commntasks-insertdata.php"
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Common Tasks-subform</title>
<meta name="viewport"charset="utf-8" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php
echo " <table border='1' #6a8fba>
<caption>SUBFORM - Common Tasks</caption>
<tr>
<th>Job Title</th>
<th>Due Date</th>
<th>Start Date</th>
<th>Cost</th>
<th>Priority</th>
<th>Percent Complete</th>
<th>Assigned To</th>
<th>Description</th>
</tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><a href= $link > $row[Title] </a></td>";
echo "<td>". $row['DueDate'] . "</td>";
echo "<td>". $row['StartDate'] . "</td> " ;
echo "<td>". $row['Cost'] . "</td>";
echo "<td>". $row['Priority'] . "</td>";
echo "<td>". $row['PercentComplete'] . "</td> " ;
echo "<td>". $row ['SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = $_GET[AssignedTo] LIMIT 1'] . "</td>";
echo "<td>". $row['Description'] . "</td> " ;
echo "</tr>";
}
}
echo "</table>";
?>
</body>
Currently, the results are being produced by this line
$result = $dbc->query($sql);
The following line will not execute a mysql query.
echo "<td>". $row ['SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = $_GET[AssignedTo] LIMIT 1'] . "</td>";
As written, you are trying to find a row value in $result that does not exist. You need to call the second query within the first while loop and pass the value of $_GET[AssignedTo] which is probably $row[AssignedTo]
Something like this
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><a href= $link > $row[Title] </a></td>";
echo "<td>". $row['DueDate'] . "</td>";
echo "<td>". $row['StartDate'] . "</td> " ;
echo "<td>". $row['Cost'] . "</td>";
echo "<td>". $row['Priority'] . "</td>";
echo "<td>". $row['PercentComplete'] . "</td> " ;
$emp = "SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = '$row[AssignedTo]' LIMIT 1";
$result2 = #mysqli_query($dbc, $emp);
$row2 = $result2->fetch_assoc();
echo "<td>". $row2 ['Firstname'] . " ". $row2 ['Lastname'] . "</td>";
echo "<td>". $row['Description'] . "</td> " ;
echo "</tr>";
}
So, Here are my revisions to your example:
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><a href= $link > $row[Title] </a></td>";
echo "<td>". $row['DueDate'] . "</td>";
echo "<td>". $row['StartDate'] . "</td> " ;
echo "<td>". $row['Cost'] . "</td>";
echo "<td>". $row['Priority'] . "</td>";
echo "<td>". $row['PercentComplete'] . "</td> " ;
$emp = "SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = '$row[AssignedTo]'";
$result2 = #mysqli_query($dbc, $emp);
$row2 = $result2->fetch_assoc();
echo "<td>". $row2['LastName']," , ",$row2[FirstName] . "</td>";
echo "<td>". $row['Description'] . "</td> " ;
echo "</tr>";
}
}
echo "</table>";
?>
Which produces this: Results of modified code
Thank you so much for your Help!
Since I am converting an Access Database to mySQL and recreating all of the queries, forms, and reports.... I am sure I will have an overwhelming amount of questions in the near future.
Eric

php - How to find out the order no. of a row while displaying values?

I have code that takes values from a database that belong to a particular user.
<?php
$user = $_SESSION['username'];
$q = intval($_GET['q']);
$db = mysqli_connect('localhost', 'username', 'password', 'database_name');
$sql = "SELECT * FROM savedtimes WHERE username = '$user' AND session = '$q' ORDER BY timeid";
$result = mysqli_query($db, $sql);
//$SNo = I might need to put something over here which makes it show the order number.
echo "<table>
<tr>
<th>S.No.</th>
<th>time</th>
<th>Avg of 5</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $SNo . "</td>";//This is the S.no column.
echo "<td>" . $row['value2'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Now, while it is displaying these values in the order of a field called timeid, which is on auto increment, I want to have a column called S.No (only while displaying, not in the actual database), which orders them from 1 to the last number. Please note that I can't just use 'timeid', because I have multiple users, so the numbers won't be continuous. So basically, the order is that of 'timeid', but I want a column showing up with continuous numbers. How do I do this?
Declare a counter variable (with a value of 1) outside of the while() loop. Display it inside the loop and subsequently increment it at the end of the loop.
// your code
$SNo = 1;
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $SNo . "</td>";
echo "<td>" . $row['value2'] . "</td>";
echo "</tr>";
++$SNo;
}
// your code

It is expected to get all the row from mysql but getting first one

I am trying to get all values shown in a table from mysql but getting one .
I want to get the rows of the mysql table at in the last table mentioned in the code
////////Here is a desc of no use --- blah for just posting this question / as i am getting an error msg for giving more details information about this question /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Here is the code:
$sql = 'SELECT
item_added
FROM
products_added
ORDER BY id';
$results = mysqli_query($conn, $sql);
if(mysqli_num_rows($results) < 1){
echo "No items";
}else{
$new_sql = 'SELECT
item_added,
quantity,
amount,
sum(amount) as items_total
FROM
products_added
where `username` = "'.mysqli_real_escape_string($conn, $_SERVER["REMOTE_ADDR"]).'"
ORDER BY id';
$resu = mysqli_query($conn, $new_sql);
}
?>
<table>
<thead>
<tr>
<td>Item</td>
<td>Qyt</td>
<td>Price</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($resu)){
echo "<tr>";
echo "<td>" . $row['item_added'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "<td>" . $row['amount'] . "</td>";
echo "<td><a class=\"remove-from-cart\" href=\"\"><i class=\"fa fa-times\"></i></a></td>";
echo "</tr>";
}
?>
</tbody>
</table>
It looks like its because you're using an aggregate function SUM() without a GROUP BY. In the $new_sql query, try adding "GROUP BY item_added" right before "ORDER BY id".

PHP while-loop not working with mysql_result

I have a Physician Query:
// Primary Physician Query
$qPhysician = mysql_query("SELECT * FROM physicians ORDER BY lastName ASC, firstName ASC");
$rowPhysician = mysql_fetch_array($qPhysician);
// State Query for Physician
$idStatePhysician = $rowPhysician['idstate'];
$qStatePhysician = mysql_query("SELECT * FROM states WHERE idstate=$idStatePhysician");
$rowStatePhysician = mysql_fetch_array($qStatePhysician);
// City Query for Physician
$idCityPhysician = $rowPhysician['idcity'];
$qCityPhysician = mysql_query("SELECT * FROM cities WHERE idcities=$idCityPhysician");
$rowCityPhysician = mysql_fetch_array($qCityPhysician);
I have a while loop to display all physicians row to a table:
$num = mysql_num_rows($qPhysician);
$i=0;
while($i < $num)
{
$idphysicians = $rowPhysician['idphysicians'];
if ($i % 2 == 0){
echo "<tr class='even' onclick=\"DoNav('physicianUpdate.php?idphysicians=$idphysicians');\">";
}
else{
echo "<tr class='odd' onclick=\"DoNav('physicianUpdate.php?idphysicians=$idphysicians');\">";
}
echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
echo "<td>";
if(isset($rowPhysician['idcity'])){echo mysql_result($qCityPhysician,$i,"name");} else{}
echo "</td>";
$i++;
}
My problem is: I have 3 rows of data from my physicians table. Each has a value for 'idcity' reflecting the idnumber from my City table. However, the 1st row of Data displays the idcity=Name properly, but the 2nd and 3rd row gave an error:
Warning: mysql_result() [function.mysql-result]: Unable to jump to row 1 on MySQL result index 7 in C:\wamp\www\iPOC\physicians.php on line 55
Also, if I have a blank value for idcity on one of the row, it also generates an error.
Please help! Thanks in advance!
The problem is that you're using mysql_result() with a one-way result. The correct fix is to use one of the mysql_fetch_*() functions instead, checking the returned value in your while loop.
while($row = mysql_fetch_array($qPhysician)) {
...
}
Something like this would probably work better:
$qCityPhysician = mysql_query("SELECT * FROM cities WHERE idcities=$idCityPhysician");
$qCityPhysicians = array();
while($row = mysql_fetch_array($qCityPhysician)) {
$qCityPhysicians[$row['idcity']] = $row['name'];
}
$qPhysician = mysql_query("SELECT * FROM physicians ORDER BY lastName ASC, firstName ASC");
$i=0;
while($row = mysql_fetch_array($qPhysician)) {
if ($i % 2 == 0) {
echo "<tr>";
echo "<td>" . $row['lastName'] . "</td>";
echo "<td>" . $row['firstName'] . "</td>";
echo "<td>";
if(isset($row['idcity'])) {
echo $qCityPhysicians[$row['idcity']];
}
echo "</td>";
$i++;
}
}

Categories