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
Related
So I am carrying out a query and returning the results in the form of a table. The code below works well.
<table>
<thead>
<tr style="text-align: center;">
<th>Activity</th>
<th>Description</th>
<th>Frequency</th>
<th>Mandatory</th>
<th>Added Yet</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $conn->prepare("SELECT * FROM knowledgebase ORDER BY category ASC");
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) echo "<tr><td>No activities found</td><td></td><td></td><td></td><td></td><td></td></tr> </tbody>
</table></br></br>
Why not add your first activity from our Knowledge base or create a new activity of your own";
else {
while($row = mysqli_fetch_array($result)) {
$activity_id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$frequency = $row['frequency'];
$mandatory = $row['mandatory'];
echo "<tr><td>".$title."</td><td>".$description."</td><td style=\"text-align: center;\">".$frequency."</td><td style=\"text-align: center;\">".$mandatory."</td><td></td></tr>";
}
}
$stmt->close();
?>
</tbody>
</table>
What I want to add in is another query inside the final <td></td>. What I want to do is query a second db table and say if this activity has already been added to the users table, echo YES, otherwise, echo NO.
The problems is, adding the query into the while loop keeps throwing errors.
Any suggestions gratefully received.
Instead of running another query for every row, you could join the users table to the knowledgebase table in your first query. If you use a left join, you'll still get all the rows from knowledgebase.
SELECT knowledgebase.*, userstable.activity_id
FROM knowledgebase
LEFT JOIN userstable ON knowledgebase.id = userstable.activity_id
ORDER BY category ASC
Then in your last <td>, you can print YES/NO depending on whether or not there was a matching row in the users table.
...<td><?php echo $row['activity_id'] ? 'YES' : 'NO' ?></td>...
(I made up names for your other table and column, but I think it shows the general idea.)
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.
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");
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"