I have a while loop that populates a dropdown box with values from a mysql table. There are only two matching records and it is repeating them over and over. How do i only display each record once?:
$query = "SELECT * FROM members, sportevents, dates, results, event, userlogin ".
"INNER JOIN members AS m ON userlogin.id = m.id " .
"WHERE userlogin.username = '$un' " .
"AND sportevents.id = members.id " .
"AND sportevents.event_id = event.id " .
"AND sportevents.date_id = dates.id " .
"AND sportevents.result_id = results.id";
echo "<form method='POST' action='display.php'>";
echo "Please Select Your Event<br />";
echo "<select name='event'>";
echo "<option>Select Your Event</option>";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo "<option>";
echo $row['eventname'];
echo "</option>";
}
echo "</select>";
echo "<input type='submit' value='Go'>";
echo "</form>";
Have you tried running that query manually in the mysql monitor? Nothing in your code would produce an infinite loop, so most likely your query is not doing joins as you expect and is doing a cross-product type thing and creating "duplicate" records.
In particular, your query looks very suspect - you're using the lazy "from multiple tables" approach, instead of explicitly specifying join types, and you're using the members table twice (FROM members ... and INNER JOIN members). You don't specify a relationship between the original members table and the joined/aliased m one, so most likely you're doing a members * members cross-product fetch.
give that you seem to be fetching only an event name for your dropdown list, you can try eliminating the unused tables - ditch dates and results. This will simplify things considerable, then (guessing) you can reduce the query to:
SELECT event.id, event.eventname
FROM event
INNER JOIN sportevents ON event.id = sportevents.event_id
INNER JOIN members ON sportevents.id = members.id
INNER JOIN userlogins ON members.id = userlogins.id
WHERE userlogins.username = '$un'
I don't know if the members/userlogins join is necessary - it seems to just feed sportevents.id through to members, but without knowing your DB's schema, I've tried to recreate your original query as best as possible.
You could always try changing the SELECT statement to a SELECT DISTINCT statement. That'll prevent duplicates of the selected fields.
Either that or reading all the results before displaying them, then de-duping them with something like array_unique().
Checkout My Example. It will be helped for you to understand. Because this code 100% working for me. Study it and get a solution.
And You Should Use DISTINCT keyword and GROUP BY Keyword. That's the Main Thing to prevent repeating values.
<?php
$gtid = $_GET['idvc'];
if(isset($_GET['idvc']))
{
$sql = mysql_query("SELECT DISTINCT gallery_types.gt_id, gallery_types_category.gtc_id, gallery_types_category.gt_category, gallery_types_category.gtc_image FROM gallery_types, gallery_types_category WHERE $_GET[idvc]=gtid GROUP BY gt_category");
mysql_select_db($database,$con);
while($row = mysql_fetch_array($sql))
{?>
<table>
<tr>
<td width="100px"><?php echo $row['gt_id'] ?></td>
<td width="100px"><?php echo $row['gtc_id'] ?></td>
<td width="300px"><?php echo $row['gt_category'] ?></td>
<td width="150px">
<a href='view_all_images.php?idvai=<?php echo $row[gtc_id] ?>' target='_blank'>
<img width='50' height='50' src='<?php echo $row[gtc_image] ?>' />
</a>
</td>
</tr>
</table>
<?php
}
}
?>
Better Understand, Follow Following Method,
$sql = mysql_query("SELECT DISTINCT table1.t1id, table2.t2id, table2.t2name FROM table1, table2 WHERE t1id=t2id GROUP BY t2name");
Related
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.
I have one MySQL table and it has two columns -
I want to display in my site like this -
I can easily take the table name Boy | Girl . But when i try to display the table I get like this -
I am just showing one example here. There may be 50 boys and 10 girls.. So I need help.
After displaying the heading
while($row_type = mysql_fetch_array($type))
{
$type_name = $row_type['type_name']; //Boy (or) Girl taking from another table
$type_name = Database::getInstance()->query("SELECT * FROM details WHERE type='type_name'");
echo "<tr>";
while($row_name = mysql_fetch_array($type_name))
{
echo "<td>$row_name[type_name]</td>"; //Displaying the names
}
echo "</tr>";
}
So many views but not getting any answer. Please help guys. Please catch my mistake.
Try with two queries.
Make an array for each category(Male & Female)
It Works.
$maleQuery = mysql_query("SELECT * FROM table WHERE category='male'");
$femaleQuery = mysql_query("SELECT * FROM table WHERE category='female'");
while(($row = mysql_fetch_assoc($maleQuery))) {
$males[] = $row['name'];
}
while(($row = mysql_fetch_assoc($femaleQuery))) {
$females[] = $row['name'];
}
$number_of_rows = max(sizeof($males),sizeof($females));
echo "<table border='1'>";
echo "<tr><td>Male</td><td>Female</td></tr>";
for($i=0;$i<$number_of_rows;$i++)
{
echo "<tr><td>".#$males[$i]."</td><td>".#$females[$i]."</td></tr>";
}
Try this query 100% working but set php code.
SELECT IFNULL(c.Boy,'')AS Boy,IFNULL(c.Girl,'')AS Girl FROM
(SELECT x.name,CASE WHEN (x.category = 'boy') THEN x.name END AS Boy,CASE WHEN (x.category = 'girl') THEN x.name END AS Girl FROM (SELECT * FROM tablename) X)c
Is your problem to do with the creation of the table using PHP or is it related to the SQL query itself?
If it is the creation of the table then I suggest you use two tables embedded in a single table like this. That way you can build the first table using one SQL query, then build the second table using a second query, then display the table and girls and boys will appear side by side regardless of how many entries on each side. Your code would look a bit like this:
echo "<table>
<tr>
<td>
<table>
<tr><th>Boy</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Boy'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
<td>
<table>
<tr><th>Girl</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Girl'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
</tr>
</table>";
If you need to cater for more categories, do an initial search to determine the distinct categories, then put the section of code above that creates the inner table in a loop.
eg. in pseudo code:
echo the outer table <table><tr>
SELECT DISTINCT Category FROM details
while row1=get next category
$cat = row1[0];
echo "<td>
<table>
<tr><th>".$cat."</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = '".$cat."'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
echo the </tr></table> to close the outer table
I'm trying to do nested mysql query but I'm failing
it's as simple as I have a table called 'todo' which is for saving to-do list
when I do
well this code is just to show how I wanna do it logically , I know it doesn't work
and I think it probably needs JOIN or UNION but I couldn't do it
$result = mysqli_query($con,"SELECT type FROM todo WHERE user = '$username' GROUP BY type");
while($row = mysqli_fetch_array($result))
{
echo '<td>- '." ".$row['type'].'</td>';
echo "</br>";
$result2 = mysqli_query($con,"SELECT titleFROM todo WHERE type= '$row['type']'");
while($row = mysqli_fetch_array($result2))
{
echo '<td>-- '." ".$row['title'].'
}
</td>';
echo "</br>";
}
I want the result to like
-Work
--Mr Jack
--Company
-School
--Android Class
--Entrepreneurship
--php development
and so on...
Your inner loop overwrites the outerloop's $row variable. Try using a different variable name in the inner loop. Also, there's an error in your inner loop's SQL query (missing space between the tablename and FROM keyword).
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.
OK,
In this query I am displaying the sales for a particular person, matching the passport number from the current form I am working on.
What I want to do however, is to sum the total sales and display it, excluding records which have been marked as paid.
I am having trouble because "paid" does not existent in the current form I am working on as a variable, nor the table it relates to.
I canĀ“t use row['paid'] as I need to do this query outside of the while loop.
What should I do in this situation?
$sqlstr = mysql_query(
"SELECT * FROM sales where passport = ".
"'{$therecord['passport']}'");
if (mysql_numrows($sqlstr) != 0) {
echo "<b>Sales for {$therecord['firstname']} ".
"{$therecord['lastname']}</b><br />";
echo "<table><tr>";
echo '<tr><th align="left">Name</th><th align="left">Quantity</th>".
"<th align="left">Cost</th></tr>';
while ($row = mysql_fetch_array($sqlstr)) {
echo "<td>{$row['product']}</td>";
echo "<td>{$row['quantity']}</td>";
echo "<td>{$row['cost']}</td>";
echo "</tr>";
}
}
echo "</table>";
$sqltotal = mysql_query(
"SELECT SUM(cost) as total FROM sales where passport = ".
"'{$therecord['passport']} AND {$therecord['paid']} <> 1'");
$row = mysql_fetch_array($sqltotal);
echo "<br /><b>Total Owing: {$row['total']}</b>";
You could either create a MySQL view, of look at SQL joins. I'm not sure on your database structure, but you should have a SQL query like this:
SELECT SUM(sales.cost) AS total
FROM sales, table2
WHERE sales.passport = '$passport_id'
AND sales.passport = table2.passport
AND table2.paid = '1'
Not sure as that was wrote off-hand. Again, it'd be better if we knew the structure of your tables.
you've misplaced simple quote in :
"'{$therecord['passport']} AND {$therecord['paid']} <> 1'"
it must be :
"'{$therecord['passport']}' AND {$therecord['paid']} <> 1"