mysql php subtract 2 fields from 2 tables Improving Query - php

hi guys im trying to improve my query for better performance is it possible to write this query in better way thanks a lot your helps
$query = " SELECT A FROM out_org where zone_id='1'";
$query2 = " SELECT A FROM out_dis where zone_id='1'";
$result = mysql_query($query);
$result2 = mysql_query($query2);
echo "<table border=1 style='background-color:#F0F8FF;' >";
echo "<caption><EM>my table</EM></caption>";
echo "<tr>";
echo "<th>" .OA. "</th>" ;
echo "<th>" .DA. "</th>";
echo "<th>" .total. "</th>";
echo "</tr>";
while($row = mysql_fetch_array($result) )
{
while( $row2 = mysql_fetch_array($result2)){
echo "<tr>";
echo "<td>" .$row['A']."</td>";
echo "<td>" .$row2['A']."</td>";
echo "<td>" .$total = $row['A'] - $row2['A']."</td>";
echo "</tr>";
}
echo "</table>";
}

Change your SQL to one query using a join and do the subtraction within the query:
$query = "SELECT (o1.A - o2.A) as value
FROM out_org o1
LEFT JOIN out_dis o2
ON o1.zone_id = o2.zone_id
WHERE o1.zone_id='1'";

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

Calculating Age Sql query

good day guys i have my code here to get age from date of birth stored in my database.
$connect=mysql_connect("localhost","root","");
mysql_select_db("mydb",$connect);
$query = "select date_format(now(), '%Y') - date_format(dob, '%Y') - (date_format(now(), '00-%m-%d') < date_format(dob, '00-%m-%d'))
as age from data";
$result = mysql_query($query);
$values = mysql_fetch_assoc($result);
$age = $values['age'];
$query="select * from data";
$result=mysql_query($query);
if(mysql_num_rows($result)>0){
echo "<table align='center' border='1'>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>Last Name</th>";
echo "<th>First Name</th>";
echo "<th>Age</th>";
echo "</tr>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$age."</td>";
echo "</tr>";
}
echo "</table>";
}
all data is fetch but the only problem is the age of the first row is the same as the rest of my data. what wrong with my code? anybody help please thank you.
You are printing pre-fetched age from values array.
Instead read from current row and use to display.
Change your SQL query as below:
$query = "select id, lname, fname,
date_format(now(), '%Y') - date_format(dob, '%Y')
- ( date_format(now(), '00-%m-%d')
< date_format(dob, '00-%m-%d'))
as age
from data";
Change:
echo "<td>".$age."</td>";
To:
echo "<td>".$row['age']."</td>";
The problem is you are fetching the age for single time, get the dob in while loop and then calculate the age and print the age in while loop itself.
You are getting age once and using it for rest of your data.
Try something like this:
<?php
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("mydb", $connect);
$query = "select * from data";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
echo "<table align='center' border='1'>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>Last Name</th>";
echo "<th>First Name</th>";
echo "<th>Age</th>";
echo "</tr>";
while ($row = mysql_fetch_array($result)) {
$query1 = "select date_format(now(), '%Y') - date_format(dob, '%Y') - (date_format(now(), '00-%m-%d') < date_format(dob, '00-%m-%d'))
as age from data where id = $row[id]";
$result1 = mysql_query($query);
$values1 = mysql_fetch_assoc($result);
$age = $values1['age'];
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $age . "</td>";
echo "</tr>";
}
echo "</table>";
}
Considering your age formula is right, try this query.
// query will give all records and age for each record.
$query="SELECT a.*, (SELECT TIMESTAMPDIFF(YEAR,dob,NOW()) FROM data AS b WHERE a.id = b.id) AS age FROM data AS a";
// rather than getting two result sets, you have age in the same record now, access it as a field.
$result=mysql_query($query);
if(mysql_num_rows($result)>0){
echo "<table align='center' border='1'>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>Last Name</th>";
echo "<th>First Name</th>";
echo "<th>Age</th>";
echo "</tr>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['age']."</td>"; // get age from db results
echo "</tr>";
}
echo "</table>";
}

How to display records in table with top 10 enteries with specific colour

I an trying to display records in table with top 10 enteries with specific color
My Query just for Ref.
$sqlsum=mysql_query("SELECT `userid`, SUM(`points`) as `total` FROM
`tablename` GROUP BY `userid` ORDER BY total DESC LIMIT 10");
This code below displays a simple table, I need to display table With TOP 10 entries be different in colour[blue].. rest remains the same [white background].
i.e Top 10 can be in blue color, and rest in white color.
Below is the code I am using to display records.
<?php
while($row = mysql_fetch_array($sqlsum))
{
echo "<tr> ";
echo "<td>" .$row[userid] . "</td>";
echo "<td>" .$row[total] . "</td>";
}
echo "</tr> " ;
?>
I have this table structure as sample. That I want to use, with this code. The table need to be the same , but i am not to find the logic , how to build the table
with this structure
<table>
<thead><tr><td colspan="2"><center>Prizes</center></td></tr><tr>
<th>Position</center></th><th><center>Prize</center></th></tr></thead>
<tbody><tr><td>1st</td><td>0.0$</td></tr>
<tr class="alt"><td>2nd</td><td>0.0$</td></tr>
<tr><td>3rd</td><td>0.0$</td></tr>
<tr class="alt"><td>4th</td><td>0.0$</td></tr>
<tr><td>5th</td><td>0.0$</td></tr>
</tbody>
</table>
Remove Limit 10 For Fetch All Data:
$sqlsum=mysql_query("SELECT `userid`, SUM(`points`) as `total` FROM
`tablename` GROUP BY `userid` ORDER BY total DESC");
php:
<?php
$i=1;
while($row = mysql_fetch_array($sqlsum))
{
echo "<tr ".(($i <= 10) ? "bgcolor='blue'" : '')'."> ";
// Apply attrinute bgcolor for backgroung color
echo "<td>" .$row[userid] . "</td>";
echo "<td>" .$row[total] . "</td>";
echo "</tr>";
$i++;
}
?>
Set an indicator variable to point it.
<?php
$rowNumber = 0;
while($row = mysql_fetch_array($sqlsum))
{
if ($rowNumber < 10)
{
echo "<tr class=\"alt\"> ";
}
else
{
echo "<tr> ";
}
echo "<td>" .$row[userid] . "</td>";
echo "<td>" .$row[total] . "</td>";
echo "</tr> " ;
$rowNumber++;
}
?>

Using data from first mysqli query in second query and nesting results

I have multiple tables I am joining to use in results for a second query and nesting the second results inside the first results.
I am using the following code:
$result = mysqli_query($con,"SELECT info.lotto_id, info.name, info.number_balls, info.number_bonus_balls, info.db_name, country.name_eng AS country, currency.name AS currency, currency.symbol AS symbol, next.draw_date AS next_draw, next.jackpot AS next_jackpot
FROM info
LEFT JOIN country ON info.country_id = country.id_country
LEFT JOIN currency ON info.currency_id = currency.currency_id
LEFT JOIN next ON info.lotto_id = next.lotto_id
WHERE (info.active='1')
ORDER BY next_jackpot DESC");
while($lotto = mysqli_fetch_array($result))
{
echo "<table border='0' width='600px' align='center'>";
echo "<tr>";
echo "<td>";
echo "<h1>Results for:</h1>";
echo "</td>";
echo "<td align='right'>";
echo "<p><img src='images/". $lotto['lotto_id'] ."_big.png' alt='". $lotto['name'] ." Results'/></p>";
echo "</td>";
echo "</tr>";
echo "</table>";
$result2 = mysqli_query($con,"SELECT * FROM" .$lotto['db_name'].
"ORDER BY date DESC
Limit 3");
while($draw = mysqli_fetch_array($result2))
{
echo "<table class='results' align='center'>";
echo "<tr>";
$draw['display_date'] = strtotime($draw['date']);
$lotto['cols'] = $lotto['number_balls'] + $lotto['number_bonus_balls'];
echo "<td class='date' colspan='".$lotto['cols']."'>".date('D M d, Y', $draw['display_date']). "</td>";
if ($draw[jp_code] < "1")
{
echo "<td class='winner' align='center'>Jackpot Amount</td>";
}
else
{
echo "<td class='rollover' align='center'>Rollover Amount</td>";
}
It is giving me the following error: Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /home/content/95/11798395/html/results/info_mysqli.php on line 59
This relates to my results2 query. Can somebody please suggest what I am doing wrong.
Thank you.
Change:
$result2 = mysqli_query($con,"SELECT * FROM" .$lotto['db_name'].
"ORDER BY date DESC
Limit 3");
to:
$result2 = mysqli_query($con, "SELECT * FROM {$lotto['db_name']} ORDER BY date DESC LIMIT 3");
if ($result === false) {
exit("Error: " . mysqli_error($con));
}

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