Display Multiple PHP Queries - php

I need to display multiple queries (they can't be combined into one large query, at least I don't think so) together in a webpage. I'll explain a little about the queries to give an idea of the problem. I have a database in MySQL with 3 question tables of the same format linked to a response table via a classid. The response table is linked to an instructor table via an instructorid. I need to display a table showing all 3 question scores for each record existing for an instructor, with each table followed by some text indicating which question had the highest value as well as the least. I created a uniontbl view in MySQL which is a union query with fields ClassID, Average and TableName. What I have so far is:
$query2 = "SELECT `tbl_instructor`.`FirstName`,
`tbl_instructor`.`LastName`,
`tbl_term`.`TermID`,
`tbl_ucourse`.`Abbreviation`,
`tbl_ucourse`.`Series`,
`tbl_uquestion01`.`Average` AS `Q1`,
`tbl_uquestion02`.`Average` AS `Q2`,
`tbl_uquestion03`.`Average` AS `Q3`
FROM `tbl_instructor`
LEFT JOIN `undergrad`.`tbl_uresponse` ON `tbl_instructor`.`InstructorID` = `tbl_uresponse`.`InstructorID`
LEFT JOIN `undergrad`.`tbl_ucourse` ON `tbl_uresponse`.`CourseID` = `tbl_ucourse`.`CourseID`
LEFT JOIN `undergrad`.`tbl_Term` ON `tbl_UResponse`.`TermID` = `tbl_Term`.`TermID`
LEFT JOIN `undergrad`.`tbl_uquestion01` ON `tbl_uresponse`.`ClassID` = `tbl_uquestion01`.`ClassID`
LEFT JOIN `undergrad`.`tbl_uquestion02` ON `tbl_uresponse`.`ClassID` = `tbl_uquestion02`.`ClassID`
LEFT JOIN `undergrad`.`tbl_uquestion03` ON `tbl_uresponse`.`ClassID` = `tbl_uquestion03`.`ClassID`
WHERE CONCAT(LastName, ', ', FirstName, ' (', UserID, ')') = '{$instructor}'";
$query3 = "SELECT `tbl_instructor`.`FirstName`,
`tbl_instructor`.`LastName`,
`uniontbl`.`ClassID`,
`uniontbl`.`TableName`,
`tbl_uresponse`.`InstructorID`
FROM `tbl_Instructor`
LEFT JOIN `undergrad`.`tbl_uresponse` ON `tbl_instructor`.`InstructorID` = `tbl_uresponse`.`InstructorID`
LEFT JOIN `undergrad`.`uniontbl` ON `tbl_uresponse`.`ClassID` = `uniontbl`.`ClassID`
WHERE CONCAT(LastName, ', ', FirstName, ' (', UserID, ')') = '{$instructor}'
ORDER BY `uniontbl`.`Average` DESC
LIMIT 1";
$query4 = "SELECT `tbl_instructor`.`FirstName`,
`tbl_instructor`.`LastName`,
`uniontbl`.`ClassID`,
`uniontbl`.`TableName`,
`tbl_uresponse`.`InstructorID`
FROM `tbl_Instructor`
LEFT JOIN `undergrad`.`tbl_uresponse` ON `tbl_instructor`.`InstructorID` = `tbl_uresponse`.`InstructorID`
LEFT JOIN `undergrad`.`uniontbl` ON `tbl_uresponse`.`ClassID` = `uniontbl`.`ClassID`
WHERE CONCAT(LastName, ', ', FirstName, ' (', UserID, ')') = '{$instructor}'
ORDER BY `uniontbl`.`Average` ASC
LIMIT 1";
$result2 = mysqli_query($query2);
$result3 = mysqli_query($query3);
$result4 = mysqli_query($query4);
while($row2 = mysqli_fetch_assoc($result2))
{
echo "<br>";
echo"<table>";
echo "<tr>";
echo "<th>Q1</th>";
echo "<th>Q2</th>";
echo "<th>Q3</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row2['Q1'] . "</td>";
echo "<td>" . $row2['Q2'] . "</td>";
echo "<td>" . $row2['Q3'] . "</td>";
echo "</tr>";
echo"<br>";
echo "</table>";
while($row3 = mysqli_fetch_assoc($result3))
{
echo $row3['TableName'];
}
echo "<br>";
while($row4 = mysqli_fetch_assoc($result4))
{
echo $row4['TableName'];
}
echo "<br>";
}
So, how I've tried to tackle the problem is using the second and third queries to determine which questions had the highest and lowest score from the uniontbl view and displaying that after each table containing the question scores. The problem is that the second and third queries ONLY display after the first table (or record) and do not show at all after that. I have a feeling that the problem lies in the actual queries themselves but I can't think of another way to solve the problem. P.S. I know my code isn't the best (echoing HTML and such) but I'm just trying to get it to work...

After you print the first row of $result2, you fetch all the rows of $result3 and $result4. So after you print the second row of $result2, there's nothing left to fetch from the second and third queries.
Since the second and third queries use LIMIT 1, there's just one row for each of them. You could fetch them each once, and then display that row after each row of the first query. But I'm not sure why you need to display the same thing multiple times. Maybe you should just show the output of these two queries once, at the beginning or end, rather than after each row.
Also, do you really want to create a whole new table for each row of $result2? Usually each row is just a row in one big table, not a separate table with just one row for each row from the DB.

Related

How to show in a table results based on my DataBase? Mysql PHP

I have these 3 tables in my DB:
Conductores: id_conductor, nombre_conductor
Trayectos: id_trayecto, Trayecto, Origen, Destino, Horas_conduccion
Viajes: id_viaje, id_conductor, id_trayecto, Salida, Llegada, Horas_conduccion, Disco, Semana
The table "Viajes" is the one in which I will insert the journeis of the truck drivers(conductor) every day, and I want to calculate the drive hours and rest hours for each truck driver in a table like this one:
The Code that I have to build this table is the following:
The connection to the data base obviously...
<?php
echo "<table border='1'>";
echo "<tr>";
echo "<td><b>Conductor</b></td>";
echo "<td><b>Posicion Actual</b></td>";
// (etc.........)
echo "<td><b>Descansos 11 H.</b></td>";
echo "</tr>";
$sql="SELECT * FROM conductores ";
$resultado=mysql_query($sql);
while($row=mysql_fetch_array($resultado)){
echo "<tr>";
echo "<td valign='top'>" . nl2br($row["nombre_conductor"]) . "</td>";
echo "<td></td>";
// (etc.........)
echo "</tr>";
}
I know how to calculate columns but just for one truck driver, for instance, if I want the Current Position (Posicion Actual) for driver 1, I'll do:
$result=mysql_query("SELECT Destino FROM trayectos WHERE (SELECT MAX(id_viaje) FROM viajes WHERE id_conductor=1)");
$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo "PosiciĆ³n Actual = " . $row["Destino"];
Hours driving last week:
$result = mysql_query("SELECT SEC_TO_TIME (SUM( TIME_TO_SEC(Horas_conduccion))) as total FROM viajes WHERE id_conductor=1 AND semana=week(curdate())-1");
$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo "horas semana anterior = " . $row["total"];
And so on with the rest.
So I want to do it automatically for each truck Driver, and cover the hole table.
Could you help me? I'm a little bit lost.
Get the ids of each conductor from the list of conductors and then pass it to the query and loop it.
$result=mysql_query("SELECT Destino FROM trayectos WHERE (SELECT MAX(id_viaje) FROM viajes WHERE id_conductor='.$conductor_id)");
You will need a combination of subqueries and joins to combine all these data into a single query.
SELECT c.*, t1.maxid, tr.Destino, t2.total FROM conductores c
LEFT JOIN (SELECT id_conductor, MAX(id_viaje) maxid FROM viajes GROUP BY id_conductor) t1 on c.id_conductor = t1.id_conductor
LEFT JOIN viajes v on t1.maxid=v.id_viaje
LEFT JOIN trayectos tr on tr.id_trayecto = v.id_trayecto
LEFT JOIN (SELECT id_conductor, SEC_TO_TIME (SUM( TIME_TO_SEC(Horas_conduccion))) as total
FROM viajes
GROUP BY id_conductor
WHERE semana=week(curdate())-1) t2 on c.id_conductor=t2.id_conductor
The 1st subquery retrieves the max(id_viaje) from viajes table by driver. Then I join again the viajes table to get the corresponding id_trayecto back and use that data to get the destination.
The 2nd subquery get the time summary by driver.

JOIN in MySQL and relational tables error

I have three tables, "food","member" and "member_food". I'm trying to make an update user page where a collection of tags are prepopulated by the data in "member_food".
I have debugged the ID sending from the previous page which allows me to select the entry I wish to query, ID:4.
$query = "SELECT * FROM `food` left join `member_food` on food.entityid = member_food.food_id WHERE member_id = '$id'";
//Breakfast
$breakfastresult1 = $mysqli->query($query);
echo '<select name="breakfast1">';
while($BreakfastData1 = mysqli_fetch_array($breakfastresult1, MYSQL_ASSOC))
{
echo '<p><option value="' . htmlspecialchars($BreakfastData1['member_food.food_id']) . '">'
. htmlspecialchars($BreakfastData1['member_food.food_name'])
. '</option>'
. '</p>';
}
echo '</select>';
However, the select fields appear to be empty. I think it's not pulling the correct values from my leftjoin table.
Here is an example of my member_food table:
food table:
edit this, first you have a typo (space missing in left + join) second you need to tell from which of the table member_id belong
$query = "SELECT * FROM `food` as f left join `member_food` as mf on f.entityid = mf.food_id WHERE mf.member_id = '$id'";
You can use this to plan your joins correctly. And, as Abdul pointed out, typos are bad ;)

While loop displaying result 3 times

Basicly I'm trying to make a simple news feed but I'm stuck at the moment as my while loop display the result 3 times, why is this? :/
<?php
$sql ="SELECT
*
FROM
news,
admins";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please contact the administration team';
} else {
while($row = mysql_fetch_assoc($result))
{
echo '
<div class="content_news">
<h1>' . $row['news_name'] . '</h1>
<p style="font-size:12px;">Posted by <b>' . $row['admin_name'] . '</b> on ' . $row['news_date'] . '
<p>' . $row['news_description'] . '</p>
read more
</div>
';
}
}
?>
If you'd like to see what I am talking about: http://freewallpaperblog.com/freshrp/
Ignore the last 2(those are static html not php)
your query selects data from 2 tables (news, admins) so it joins every row of 1st table with every row of 2nd table
SELECT * FROM news, admins
i recommend you to use following query
SELECT news.*, admins.admin_name FROM news
INNER JOIN admins ON news.admin_id = admins.id
where admin_id is your correct column name
You either have 3 admins or 3 rows of news. Your query makes a direct multiplication between tables. Try "left join" instead...
SELECT * FROM news
INNER JOIN admins ON admins.id = news.adminid
Or whatever adminid is in the news table.
Try the following query:
SELECT
*
FROM
news
Inner join admins on news.admin_id = admins.id
You made no JOIN statement in your SQL, as someone else has already commented on in your question. It would help if you posted the associated fields you're grabbing, but based on your $row keys, my best guess is the following should work for you (but I can't promise it will without knowing how your database is designed, I can only infer from the variable names):
$sql = "SELECT news.name, news.date, news.description, news.link, admins.name"
. "FROM news"
. "INNER JOIN admins"
. "ON news.name=admins.name"
References:
http://www.w3schools.com/sql/sql_join_inner.asp
http://www.w3schools.com/sql/sql_join_left.asp
http://dev.mysql.com/doc/refman/5.0/en/join.html

MySQL_Query from Multiple Tables with ROUND and Math

I'm trying to make a database of items for the game "EVE Online" for me and my friends to use, and I set up a SQL server and got tables created and the like, etc etc, and everything's running fine. However, I have one issue when I'm trying to import data from two different tables and compare them against each other within the same html table element. It works perfectly if I just import from one table with multiple columns, but I get issues when I try to select more than one source.
The tables I'm pulling from are...
testmetrics.eve_inv_types
and
testmetrics.items_selling
Ideally, I'd like to import the "name", "type_id", "jita_price_sell" columns from table #1, and "price", "type_id", "station_id", and "qty_avail" from table #2.
I'm also using the ROUND operator on jita_price_sell and price to get a 2 decimal approximation for price points of various items. I also have it so that in table #2 only results with the correct station_id will get displayed. But it keeps throwing up an error!
Here is my code so far...
<?php
$con = mysql_connect("testmetrics.db.10198246.xxxx.com","xxxx","xxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testmetrics", $con);
$result = mysql_query("
SELECT testmetrics.eve_inv_types.name, testmetrics.eve_inv_types.type_id, ROUND(testmetrics.eve_inv_types.jita_price_sell, 2) as jita_price_sell, ROUND(testmetrics.items_selling.price, 2) as price, testmetrics.items_selling.qty_avail, testmetrics.items_selling.sation_id, testmetrics.items_selling.type_id
FROM testmetrics.eve_inv_types, testmetrics.items_selling
WHERE testmetrics.eve_inv_types.type_id = testmetrics.items_selling.type_id, testmetrics.items_selling.station_id = '61000746'");
echo "<table class='sortable'>
<tr>
<th>Item Name</th>
<th>Price (Jita)</th>
<th>Price (K-6K16)</th>
<th>Qty Avail (K-6K16)</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['testmetrics.eve_inv_types.name'] . "</td>";
echo "<td>" . $row['jita_price_sell'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['testmetrics.items_selling.qty_avail'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Any help or insight you could give would be greatly appreciated. I'd also like to be able to do a math function where I'd go something like testmetrics.eve_inv_types.jita_price_sell + (testmetrics.eve_inv_types.volume * 300) to get shipping costs and have that exported to it's own column as well.
Anything you have to say is greatly appreciated!
EDIT: I know I'm already asking for alot of help here, but, does anyone know how to limit returns to "top 100" dependent on the column that it's sorted by? I'm using a Javascript addon to be able to sort easily!
This is the code that solved it for me!
SELECT eve_inv_types.name,
eve_inv_types.type_id,
Round(eve_inv_types.jita_price_sell, 2) AS jita_price_sell,
Round(items_selling.price, 2) AS price,
items_selling.qty_avail,
items_selling.type_id
FROM eve_inv_types
JOIN items_selling
ON eve_inv_types.type_id = items_selling.type_id
AND items_selling.station_id = '61000746'
SELECT eit.name,
eit.type_id,
Round(eit.jita_price_sell, 2) AS jita_price_sell,
Round(eis.price, 2) AS price,
eis.qty_avail,
eis.sation_id,
eis.type_id
FROM eve_inv_types eit
JOIN `items_selling` eis
ON eit.type_id = eis.type_id
AND eis.station_id = '61000746'
You can join tables (assuming you have a key that connects them), here's an example:
table A:
personId
firstName
lastName
numOfChildren
table B:
personId
streetName
cityName
countryName
Select from both (using personID as a join key):
SELECT firstName, lastName, numOfChildren, streetName, cityName, countryName
FROM tableA JOIN tableB USING (personId)
If you want to limit the result you can add:
LIMIT 100
And if you want the top 100 parents you can order by numOfChildren:
ORDER BY numOfChildren
Final Query will look like this:
SELECT firstName, lastName, numOfChildren, streetName, cityName, countryName
FROM tableA JOIN tableB USING (personId)
ORDER BY numOfChildren
LIMIT 100;
-- or --
SELECT firstName, lastName, numOfChildren, streetName, cityName, countryName
FROM tableA JOIN tableB ON (tableA.personId=tableB.personId)
ORDER BY numOfChildren
LIMIT 100;
Read more about join here: http://dev.mysql.com/doc/refman/5.1/en/join.html

How to reference another table with a consistent primary key across tables

I have two tables which both have a unique PID. I need to know how I should setup the primary/foreign keys so I can access fields from both tables in one SQL statement.
For example: With the following data structure i'd like to echo out the players name and photo but also echo out all their stats via PHP as well. I have successfully done this with just the player Stats, but I do not know how to get access to fields in another table.
Here is my database structure so far:
Players
-PID (Set as Primary Key)
-Name
-Height
-College
-Photo
Stats
-PID
-Touchdowns
-Receptions
Current PHP Code:
$query="
SELECT * FROM Stats
ORDER BY Stats.FantasyPoints DESC";
$res=mysql_query($query);
$num=mysql_numrows($res);
$i=0;
while($i< $num){
$Name = mysql_result($res, $i, "Name");
$FantasyPoints = mysql_result($res, $i, "FantasyPoints");
echo $Name . ': '. $FantasyPoints . "<br />";
$i++;
}
$sql = "
SELECT p.*, s.*
FROM Players AS p
LEFT JOIN Stats AS s ON p.PID = s.PID
ORDER BY s.FantasyPoints DESC
";
You could also use a JOIN rather than a LEFT JOIN which would limit the result to only players who have stats
Edited sql to produce result similar to your own sql.
======================================================
This is how I would go about it...
$query =
"
SELECT s.*, p.*
FROM Stats AS s
LEFT JOIN Players AS p ON p.PID = s.PID
ORDER BY s.FantasyPoints DESC
";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res))
{
echo "{$row['name']}: {$row['FantasyPoints']}<br />";
}

Categories