PHP while-loop not working with mysql_result - php

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++;
}
}

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>";
}

Display name instead ID from another table

I'm facing a problem to display a name on a table, only the id is displayed I have tried some inner join queries without luck i got 2 tables
Table 1 = empresas
Here is where all the data lives:
the number 9 in u_tip corresponds to the ID of the data that is in tipoempresas table
Table 2 = tipoempresas
I want to display the name of the type not the ID
I'm using this code to display the data in a html table
$result = mysqli_query($conn,"SELECT * FROM empresas");
$i = 0;
while($row = $result->fetch_assoc())
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
You are already there you just need to use join statement and specify the column you want to display
$result = mysqli_query($conn,"SELECT * FROM empresas AS e INNER JOIN tipoempresas AS t ON t.id = e.u_tip");
$i = 0;
while($row = $result->fetch_assoc())
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value['Nombre'] . "</td>"; //SPECIFY THE COLUMN YOU WANT TO DISPLAY
}
echo "</tr>";

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

sorting row data in table 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;

select data from two tables, return data and get product name from item id

<?php
$transactionOutput = "";
$sql = mysql_query("SELECT * FROM transactions WHERE emailaddress='$email'");
$productCount = mysql_num_rows($sql);
if($productCount > 0) {
while($row = mysql_fetch_array($sql)) {
$item_id = $row["item_id"];
$quantity = $row["quantity"];
$size = $row["size"];
$price = $row["price"];
$sql = mysql_query("SELECT * FROM products WHERE id='$item_id'");
$productCount = mysql_num_rows($sql);
while($row = mysql_fetch_array($sql)) {
$product_name = $row["product_name"];
}
$transactionOutput .= "<tr>";
$transactionOutput .= "<td align='center'>" .$product_name. "</td>";
$transactionOutput .= "<td align='center'>" .$quantity. "</td>";
$transactionOutput .= "<td align='center'>" .$size. "</td>";
$transactionOutput .= "<td align='center'>" .$price. "</td>";
$transactionOutput .= "</tr>";
}
} else {
$transaction_list = "You have made no transactions yet";
}
?>
I'm trying to access data from two different tables and then return the product name of each item by matching the id in the product table with the item_id returned from the transactions table. This does output the correct information however it only shows the first transaction and no others, i know this is also probably horribly programmed too
The problem seems to be that you are using the same variable $sql to store the resultsets from both the queries. So what might be happening here is this:
the transaction query runs and the resultset is stored in $sql
first record is read from the transaction resultset
for the first transaction record, the product query runs and the resultset is stored again in $sql
the output is stored into $transactionOutput
next record is read from the transaction resultset
AND the step 5 is the problem because the original transaction resultset - $sql - was overwritten by the product resultset.
Try using another variable for the product query:
$rsProduct = mysql_query("SELECT * FROM products WHERE id='$item_id'");
$productCount = mysql_num_rows($rsProduct);
while($row = mysql_fetch_array($rsProduct)) {
$product_name = $row["product_name"];
}
Hope the above makes sense!
EDIT: as an additional suggestion, you may like to try using JOIN queries to retrieve both transaction and product in the same query. Here:
SELECT `t`.*, `p`.`product_name`
FROM `transactions` `t`
LEFT JOIN `products` `p` ON `t`.`item_id` = `p`.`id`
WHERE `t`.`emailaddress` = '$email';
Just loop the resultset and you are done!
<?php
$transactionOutput = "";
$sql = mysql_query("SELECT * FROM transactions WHERE emailaddress='$email'");
$productCount = mysql_num_rows($sql);
if($productCount > 0) {
while($row = mysql_fetch_array($sql)) {
$item_id = $row["item_id"];
$quantity = $row["quantity"];
$size = $row["size"];
$price = $row["price"];
$sql = mysql_query("SELECT * FROM products WHERE id='$item_id'");
$productCount = mysql_num_rows($sql);
#I suggest you use a different variable (i.e. not $row) here;
#at this point $row from the first while is still in scope
#and clobbering it may be causing the problem you see with
#only the first transaction showing.
while($row = mysql_fetch_array($sql)) {
#If you only need the first product_name, then you don't need the loop, just
#$row2=mysql_fetch_arrqy($sql);
#$product_name = $row2["product_name"];
$product_name = $row["product_name"];
}
$transactionOutput .= "<tr>";
$transactionOutput .= "<td align='center'>" .$product_name. "</td>";
$transactionOutput .= "<td align='center'>" .$quantity. "</td>";
$transactionOutput .= "<td align='center'>" .$size. "</td>";
$transactionOutput .= "<td align='center'>" .$price. "</td>";
$transactionOutput .= "</tr>";
}
} else {
$transaction_list = "You have made no transactions yet";
}
?>

Categories