How to create a table with data retrieved from MySQL with PHP
-------------------------
| albumID | trackID |
-------------------------
| | 1990 |
- 1 -------------
| | 1991 |
-------------------------
| | 1992 |
- -------------
| 2 | 1993 |
- -------------
| | 1994 |
-------------------------
I can generate a table from the database, but the result will be only like each result in one row
$query = "SELECT albumID, trackID
FROM songs";
$result = mysqli_query($db, $query);
echo "<table>";
echo "<tr>\n";
echo "<th>albumID</th>\n";
echo "<th>trackID</th>\n";
echo "</tr>\n";
while ($data = mysqli_fetch_array($result)) {
echo "<tr>\n";
echo "<td>$data[0]</td>\n";
echo "<td>$data[1]</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
Any help given is really appreciated!
You can do this by using a variable to keep track of the current album and only output the album once as shown below.
$current_album = ''; # initialize tracking var
while ($data = mysqli_fetch_array($result)) {
echo "<tr>\n";
if ($current_album != $data[0]) {
echo "<td>$data[0]</td>\n";
$current_album = $data[0];
} else {
echo "<td> </td>\n"; # insert empty cell
}
echo "<td>$data[1]</td>\n";
echo "</tr>\n";
}
This will have the album ID appearing in the first row for the album. If you want it to be vertically centered you can use rowspan on the td element, but in order to know how many rows each album has you will either need to update your sql query to return that or you can process the results into a multidimensional array and then loop through that to generate the output.
Maybe not the most elegant solution, but should do the trick.
$query = "select albumID as album, group_concat(trackID) as tracks from songs group by albumID";
$result = mysqli_query($db, $query);
echo "<table>";
echo "<tr>\n";
echo "<th>albumID</th>\n";
echo "<th>trackID</th>\n";
echo "</tr>\n";
while ($data = mysqli_fetch_array($result)) {
$tracks = explode(",", $data[1]);
echo "<tr>\n";
echo "<td rowspan=\"".count($tracks)."\">$data[0]</td>\n";
foreach ($tracks as $key => $value) {
echo "<td>$value</td>\n"
}
echo "</tr>\n";
}
echo "</table>\n";
Edit your query to return the numbers of tracks of the album and use that number to create a rowspan only on the first track row. I wrote a little example but I havn't tried if it works.
$query = "SELECT s.albumID, s.trackID,
( SELECT COUNT(*)
FROM songs s2
WHERE s2.albumID = s.albumID )
FROM songs s";
$result = mysqli_query($db, $query);
echo "<table>";
echo "<tr>\n";
echo "<th>albumID</th>\n";
echo "<th>trackID</th>\n";
echo "</tr>\n";
$tmpAlbum = '';
while ($data = mysqli_fetch_array($result)) {
echo "<tr>\n";
echo "<td";
if($data[2] == 1){
echo "<td>$data[0]</td>\n";
}else{
if($data[0] != $tmpAlbum){
echo "<td rowspan=\"".$data[2]."\">$data[0]</td>\n";
}
}
$tmpAlbum = $data[0];
echo "<td>$data[1]</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
Related
admin TABLE
+--------------+---------------+
| Username | Password |
+--------------+---------------+
| JOHN | 123 |
| EDWARD | 123 |
+--------------+---------------+
my code
$result = mysqli_query($connection, $query);
echo" <table >";
$row = mysqli_fetch_assoc($result);
echo "<tr>";
foreach($row as $key => $val){
echo"<th>$key</th> ";
echo "</tr>";
///////////////////////////////
$result = mysqli_query($connection, $query);
echo"<tr>";
while($row = mysqli_fetch_assoc($result)){
foreach($row as $key => $val){
echo "<td>$val</td>";
}
echo "</tr>";
}
echo "</table>";
}
So, the problem is if there is more than 1 row in the result it outputs exactly what i want for e.g if i say:
SELECT Username from admin;
+--------------+
| Username |
+--------------+
| JOHN |
| EDWARD |
+--------------+
But if there is only one row it does not show the COLUMN name and gives this warning
Select Username from admin where Username = 'JOHN';
Warning: Invalid argument supplied for foreach() on line 65
+--------------+
| JOHN |
+--------------+
Sneaky typo/logical coding error: you have a curly-bracket (brace) that's screwing everything up. Look at the end of the foreach used to generate the headings:
foreach($row as $key => $val){
echo"<th>$key</th> ";
This should be:
foreach($row as $key => $val)
echo"<th>$key</th> ";
And then remove the spurious brace at the very end.
This works (so long as there is at least 1 row to get the heaedrs):
$result = mysqli_query($connection, $query);
echo " <table >";
$row = mysqli_fetch_assoc($result);
echo "<tr>";
foreach($row as $key => $val)
echo"<th>$key</th> ";
echo "</tr>";
$result = mysqli_query($connection, $query);
echo"<tr>";
while($row = mysqli_fetch_assoc($result))
{
foreach($row as $key => $val)
{
echo "<td>$val</td>";
}
echo "</tr>";
}
echo "</table>";
I am currently extracting some timetable information from my database.
I am facing a problem that I need the rows in cols and cols in rows.
The query is as:
SELECT `courses`.`course_id`,`faculty`.`uName`,`rooms`.`room_name`,`slot_allocs`.`slot_num`
FROM `faculty`
LEFT JOIN `courses` ON `courses`.`fac_id` = `faculty`.`uName`
LEFT JOIN `depts` ON `faculty`.`dept_code` = `depts`.`dept_code`
LEFT JOIN `slot_allocs` ON `slot_allocs`.`course_id` = `courses`.`course_id`
LEFT JOIN `rooms` ON `slot_allocs`.`room` = `rooms`.`room_name`
LEFT JOIN `slots` ON `slot_allocs`.`table_name` = `slots`.`table_name` AND `slot_allocs`.`day` = `slots`.`day` AND `slot_allocs`.`slot_num` = `slots`.`slot_num`
WHERE `slot_allocs`.`day` = 1 AND `depts`.`dept_code` = 100
ORDER BY `slots`.`slot_num` ASC
After I execute my PHP file in which this query executes it's in a sequential retrieve and show, I would like to have the output -- > one after the another
> > **I want to align in the sequential manner of the period per day like this:
> >|---------------------------------------------
> >day 1| period 1 |period 2 |period 3 |period 4|
> >|----|----------|---------|---------|--------|
> >day 2| period 1 |period 2 |period 3 |period 4|
> >|---------------------------------------------
And this is my php code:
$sql = file_get_contents("eboard.sql");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<table>";
echo "<tr>";
echo "<td>";
echo " Course: ID ". $row["course_id"]." : ";
echo " Prof.:". $row["uName"]." : ";
echo " Room :".$row["room_name"]." : ";
echo " period".$row["slot_num"]."";
echo "</td>";
echo "</tr>";
echo "</table>";
}
} else
echo "0 results";
$conn->close();
The output i get : ---
Please help !!
Move the <table> out of the loop:
if ($result->num_rows > 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>";
echo " Course: ID ". $row["course_id"]." : ";
echo " Prof.:". $row["uName"]." : ";
echo " Room :".$row["room_name"]." : ";
echo " period".$row["slot_num"]."";
echo "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Ok, So this code should do it. You should read up on how tables works. W3Schools have a simple page about it. I hope this version is what you want. It is not a full solution but it shows you how to use tables.
if ($result->num_rows > 0) {
echo "<table>";
echo " <tr>";
echo " <th>Course</th>";
echo " <th>Prof.</th>";
echo " <th>Room</th>";
echo " <th>Period</th>";
echo " </tr>";
while($row = $result->fetch_assoc()) {
echo " <tr>";
echo " <td>Course: ID ". $row["course_id"]."</td>";
echo " <td>Prof.:". $row["uName"]."</td>";
echo " <td>Room :".$row["room_name"]."</td>";
echo " <td>period".$row["slot_num"]."</td>";
echo " </tr>";
}
echo "</table>";
} else {
echo "0 results";
}
I'm trying to get all the records in my database and it was successful, however I can only get 1 id value. I need to get all the id in my database and call a javascript function. In my code I can only get the id of the last record. How can I get them all?
<?php
$con = mysql_connect('localhost','root','')
or die(mysql_error());
mysql_select_db ("database_name");
$query = "SELECT * FROM news ORDER BY date DESC LIMIT 0 , 3";
$result = mysql_query($query);
echo "<table>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<th>" . $row['header'] . "</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['date'] . "</td>";
echo "</tr>";
echo "<tr>";
$position=0;
$message= $row['desc'];
$post = substr($message,$position,300);
echo "<td>" . $post . "...</td>";
echo "</tr>";
echo "<tr>";
$id = $row['id'];
echo "<tr><td>";
/*The start of chaos */
echo "<form action='' method='post' onSubmit='ReadMore()'>";
for($ctr=1;$ctr<=3;$ctr++){
$id=$ctr; //This should change and increment the value of id, isn't it?
echo "<input type='hidden' name='more' value=".$id." id='more'/>";
}
echo "<input type='submit' name='read' value='Read More'>
</form>
</td></tr>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
What's happening here is that it will display records from the database: $row['header'], $row['date'], $row['desc'] then a button which says Read More in a loop. What I would like to happen is to call a function after clicking 'read more', depending on the id.
For example,
___________________________
| This is the header |
| Date |
| Description |
| Read More Button | //this button should display $id = 3
___________________________
| This is the header |
| Date |
| Description |
| Read More Button | //this button should display $id = 2
___________________________
| This is the header |
| Date |
| Description |
| Read More Button | //this button should display $id = 1
___________________________
Is that possible? or am I missing something. My code only displays $id=1 for all the buttons. I'm sorry for this.
you may try like this
make the id field name as array like more[] and bring the form out side loop as shown
no need of for loop there to get the ids u already using while loop
bring submit button also outside loop
if u want to show the details of that post then why again u using form u can simply link it to the details page n can pass the id no need to submit it as a form .
check the code below
<?php
$con = mysql_connect('localhost','root','')
or die(mysql_error());
mysql_select_db ("database_name");
$query = "SELECT * FROM news ORDER BY date DESC LIMIT 0 , 3";
$result = mysql_query($query);
//echo "<form action='' method='post' onSubmit='ReadMore()'>";
echo "<table>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<th>" . $row['header'] . "</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['date'] . "</td>";
echo "</tr>";
echo "<tr>";
$position=0;
$message= $row['desc'];
$post = substr($message,$position,300);
echo "<td>" . $post . "...</td>";
echo "</tr>";
echo "<tr>";
$id = $row['id'];
echo "<tr><td>";
/*The start of chaos */
//for($ctr=1;$ctr<=3;$ctr++){
//$id=$ctr; //This should change and increment the value of id, isn't it?
//echo "<input type='hidden' name='more[]' value=".$id." id='more[]'/>";
//}
echo "<tr><td><a href='post_details.php?post_id=".$id."'>Read More</a></td></tr>";
</td></tr>";
echo "</tr>";
}
echo "</table>";
//echo "</form>";
mysql_close($con);
?>
I am making a soccer site. I have the following table structure:
season1 (name of the table)
id | player1 | player2 | score
I want to put the scores into a html table. This table is only for player called nickname1 vs every other player. I have this:
$query = mysql_query("SELECT * FROM season1 WHERE player1='nickname1'") or die(mysql_error());
while($row = mysql_fetch_array( $query )) {
echo "<tr><td>";
echo "";
echo "</td><td>";
echo $row['score2'];
echo "</td><td>";
echo $row['score3'];
echo "</td><td>";
echo $row['score4'];
echo "</td><td>";
echo $row['score5'];
echo "</td></tr>";
}
echo "</table> <br>";
Instead of $row['score2'] I need the score between nickname1 vs
nickname2
Instead of $row['score3'] I need the score between nickname1 vs
nickname3
Instead of $row['score4'] I need the score between nickname1 vs
nickname4
Instead of $row['score5'] I need the score between nickname1 vs
nickname5
I tried SELECT * FROM season1 WHERE player1='nickname1' AND player2='nickname2' but then it will show only player1 vs player2 in the table. I want to show all 4 players vs player1 in the same table.
Assuming score1 it's player 1 score:
$query = mysql_query("SELECT * FROM season1 WHERE player1='nickname1'") or die(mysql_error());
while($row = mysql_fetch_array( $query )) {
echo "<tr><td>";
echo "";
echo "</td><td>";
echo $row['player1']." vs ".$row['player2'].", with a score of: ".$row['score'];
echo "</td></tr>";
}
echo "</table> <br>";
I hope it helps.
Saludos ;)
You need to focus your loop only on making one row:
echo "<table><tr>";
while($row = mysql_fetch_array( $query )) {
echo "<td>{$row['score']}</td>";
}
echo "</tr></table>";
This will ONLY output the scores of the players. You can modify it to have nickname headers and so forth.
Take note that the $row array resembles your table structure. $row['score'] will give you the scores of the players where as since score1 is not a column in the table, it does not exist in $row.
Possible design:
echo "<table><tr><th>Player 1</th><th>Player 2</th><th>Score</th></tr><tr>";
while($row = mysql_fetch_array( $query )) {
echo "<td>{$row['player1']}</td>";
echo "<td>{$row['player2']}</td>";
echo "<td>{$row['score']}</td>";
}
echo "</tr></table>";
will output (depending on ID's in database)
Player 1 | Player 2 | Score
p1 p2 0
p1 p3 0
NOTICE: MySQL_* has been deprecated in PHP 5.5. Use MySQLi or PDO instead
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++;
}
}