While statement help (PHP) - php

My database contains both questions and answers. The questions have an ID (intQAID) and the responses have an ID (intResponseID). The intRespondID is the same as the intQAID ID that it is responding to. Each entry into the database has its own ID, which is intPostID.
What's i'm trying to do is write a query that will grab all this information and post it to a website using a while statement. However, the structure needs to be Question and underneath be the answer, until the while loop ends.
I can get the questions to post:
$question = mysql_query("SELECT *,
(SELECT cUsername FROM tblUsers tblU WHERE Q2.intPosterID = tblU.intUserID) AS username,
(SELECT DATE_FORMAT(dPostDateTime, '%b %e %Y %H:%i')) AS post_time
FROM tblQA Q2 WHERE intResponseID = 0
ORDER BY Q2.dSortDateTime DESC, Q2.intQAID DESC LIMIT 40");
while($row = mysql_fetch_array($question))
{
echo "<tr class='forum'>";
echo "<td class='forum'>" . substr($row['cBody'], 0, 150) . "</td>";
echo "<td class='forum'>" . $row['cCategory'] . "</td>";
echo "<td class='forum'>" . $row['username'] . "</td>";
echo "<td class='forum'>" . $row['post_time'] . "</td>";
echo "</tr>";
}
But how can I get it to post the answer in the same while statement?
Should output like so:
Question 1:
Answer 1:
Question 2:
Answer 2:
Question 3:
Answer 3:
etc....

Join the table on itself:
SELECT
*,
(SELECT cUsername FROM tblUsers tblU WHERE Q2.intPosterID = tblU.intUserID) AS username,
(SELECT DATE_FORMAT(dPostDateTime, '%b %e %Y %H:%i')) AS post_time
FROM tblQA Q2
JOIN tblQA AS tblQAjoin ON tblQAjoin.intRespondID = Q2.intPostID
WHERE Q2.intResponseID = 0
ORDER BY Q2.dSortDateTime DESC, Q2.intQAID DESC
LIMIT 40
I'm not sure why you would want to design your table this way, though. If there can just be one answer per question, why not simply have two columns in a row, one containing the question and the other one the answer?

Try using a JOIN statement. As long as your questions and answers are one-to-one, you should be able to pull everything in one fell swoop.
http://dev.mysql.com/doc/refman/5.0/en/join.html

If every question has only one answer, then you should get the data for both in the one query by joining the questions table with the answers table using intRespondID and intQAI.
Then each trip through the while loop has a , whatever you want on the first line, a , a , whatever you want on the second line, and finally a . So one trip through the loop doesn't have to just show one line of output.

Related

Display Multiple PHP Queries

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.

Display same values in rows in mysql and print column value and it's count in php

I want to make a voting list kind of thing. I have a form that saves the entered data to mysql database. Suppose a user entered "Something". It'll be saved in column called "bname". Now what I want is Suppose 10 people entered "Something" or "something"(case sensitivity to be ignored automatically if there is a way?) then I want: "Something - 10" to be printed in php page.
My try:
$query="SELECT bname, count
FROM brandnames
GROUP BY bname
HAVING COUNT(*) > 0
LIMIT 11";
$result=mysqli_query($con,$query) or die('Error!: ' . mysqli_error($con));
$query2="SELECT count
FROM brandnames
GROUP BY count
HAVING COUNT(*) > 0
ORDER BY count DESC
LIMIT 11";
$result2=mysqli_query($con,$query2) or die('Counting Error!: ' . mysqli_error($con));
while ($row=mysqli_fetch_assoc($result))
{
while ($row2=mysqli_fetch_assoc($result2))
{
echo ($row['bname'] . '&nbsp' . '-' . '&nbsp' . $row2['count'] . '<br />');
}
}
This thing prints
Something - 4
Something - 3
I do not want to use this method. I posted this as if I don't post someone will point me out to post. :/
I don't want to use "count" column. I want a simple voting list as I mentioned above.
Thanks, :)
The query your looking for should be something like
select bname, count(*) as nbr
from brandnames
group by bname
order by nbr desc
limit 11;
count(*) will return the number of rows that was grouped together by bname. Case sensitivity is depending on your coalition. If it's a case sensitive coaltion you need to group by lower(bname) instead. Be aware thou that this might prevent indexes from working for this query.
Thanks all of you. I got to know how to do this. Hope this helps someone :)
Special thanks to #Andreas Wederbrand
<?php
//Create Connection
$query="SELECT columnname, count(*)
AS alias
FROM tablename
GROUP BY columnname
ORDER BY alias DESC";
$result=mysqli_query($con,$query) or die('Counting Error!: ' . mysqli_error($con));
while ($row=mysqli_fetch_array($result))
{
echo ($row['columnname'] . '&nbsp' . '-' . '&nbsp' . $row['alias'] . '<br />');
}
//Close Connection
?>

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

Get records from database in table with rowspan

I've try a lot of ways to get this table print as good as it should but I failed.
I know it's simple thing so I hope you help me with it.
Here's my code:
<?php
include('../connect.php');
$id=$_SESSION['login_user'];
$sql = "Select CourseName , Studentname from course p natural join student t";
$rs_result = mysql_query ($sql, $connection);
echo "<center>";
echo "<table>";
echo "<tr> <th>Course Name</th> <th> Students Name</th> </tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $rs_result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['CourseName'] . '</td>';
echo "<td rowspan=''> $row[Studentname] </td> ";
echo "</tr>";
}
echo "</table>";
echo "</center>";
?>
I want to be something like this
Course | Name | Student name |
Math101 | john, Mike |
...
Also, is the JOIN query between the two tables CORRECT or not?
The two tables are:
Course ( Course name - Course id )
Student ( Student name - Course id )
Try this query
$sql ="SELECT cor.CourseName,GROUP_CONCAT(stu.StudentName) AS StudentName
FROM course AS cor
LEFT JOIN student AS stu
ON stu.CourseId = cor.CourseId";
And change the the line in below
echo "<td rowspan=''>" . $row['Studentname'] . "</td> ";
This line:
echo "<td rowspan=''> $row[Studentname] </td> ";
You are accessing the array element improperly. Studentname should have single quotes around it like such:
echo "<td rowspan=''>" . $row['Studentname'] . "</td> ";
Also, in your query, this may work better:
$sql = "SELECT c.CourseName, s.StudentName
FROM course AS c
INNER JOIN student AS s
ON s.CourseId = c.CourseId";
Please use below format
SELECT CourseName , Studentname
FROM course
INNER JOIN student
ON course.id = student.id
Thanks
The problem is with Your rowspan attribute - You need to provide it with the exact number of rows to span through. Anyway, I think it is the collspan attribute You want to use, so e.g.
echo "<td collspan='2'> {$row['Studentname']} </td> ";
which means it will span through 2 columns, thus stundet's name will be both under the Name and Student name columns.
Is this what You were expecting?
Also I highly recommend not to use mysql_ functions but learn how to use mysqli or at least PDO.
I'm under the impression that you wanted to display a comma-separated list of names of all the students that attend each course, for each separate CourseName. In this case, you could change your SQL query to something like this:
SELECT CourseName, GROUP_CONCAT(Studentname SEPARATOR ', ') as names
FROM Course p NATURAL JOIN Student t
GROUP BY CourseName;
Hello please take a look of this answer. Dynamic rowspan while fetching records from database
I think it might be helpfull.

Finding the higest voted Question in last week. (sql query)

I have a 3 sql tables:
qotwQuestion1a(QuestionId [primarykey], Question, MemberId, PostDate);
qotwVote1a (QuestionId [primarykey], MemberId [primarykey], Vote1a);
qotwMember (MemberId [primarykey], Name, Password, emailId);
I want to write a sql query to find the QuetionId and MemberId of the Question that has the highest vote in the last week. I have written this query in php, but it gives me a wrong result:
$result6 = mysql_query("SELECT MAX(Vote1a) AS highestVote, * FROM qotwMember, qotwQuestion1a , qotwVote1a
WHERE qotwMember.MemberId=qotwQuestion1a.MemberId
AND qotwQuestion1a.QuestionId=qotwVote1a.QuestionId
AND qotwQuestion1a.MemberId=qotwVote1a.MemberId
AND PostDate>='".$startofweek."' AND PostDate<='".$endofweek."'
ORDER BY qotwQuestion1a.QuestionId DESC ");
while($row6 = mysql_fetch_array($result6))
{
echo "The highest voted question of the last week is: "; echo $row6['highestVote']; echo $row6['MemberId'] . " " . $row6['Name'] . " " . $row6['Password'] . " " . $row6['PostDate'] . " " . $row6['Question']." ".$row6['QuestionId']." ".$row6['Vote1a'];
echo "<br />";
}
The $startofweek and $endofweek give the date of the beginning of the last week and end of the last week.
Can someone help me with this, please.
Best
Zeeshan
SELECT *
FROM (
SELECT q.QuestionId, q.MemberID
FROM qotwQuestion1a q
JOIN qotwVote1a v
ON v.QuestionID = q.QuestionID
WHERE PostDate BETWEEN $startdate AND $enddate
GROUP BY
q.questionID
ORDER BY
COUNT(*) DESC
LIMIT 1
) qo
JOIN qotwMember m
ON m.MemberID = q.MemberID
Well, first of all, using MAX() without groupping is .. useless, you don't need it in this case. Second, if you want your results ordered from highest voted down to lowest voted, why don't you order by Vote1a and just take the first result with a LIMIT clause.
Hope you're dealing with ties somewhere ;)
And questions with no answers, for that matter.
Other than that...it looks like you're matching the member to the question, which might not make sense if your tables are set up the way they appear to be.
Try this:
SELECT Vote1a AS highestVote, *
FROM qotwMember, qotwQuestion1a , qotwVote1a
WHERE qotwMember.MemberId=qotwQuestion1a.MemberId
AND qotwQuestion1a.QuestionId=qotwVote1a.QuestionId
AND qotwQuestion1a.MemberId=qotwVote1a.MemberId
AND PostDate>='".$startofweek."'
AND PostDate<='".$endofweek."'
GROUP BY Votela, *
HAVING MAX(Votela)
ORDER BY qotwQuestion1a.QuestionId DESC");
Not too sure on the syntax of this one but the basic idea is to have a query that can get all records, and then at the last minute, isolate it to just those records having the MAX(Votela).
I would also recommend not using * unless you absolutely need it. I know it can be a pain if you want most of the columns in the tables, but it is always best practice to only select the columns you need.

Categories