Is there anyway to achieve displaying query results into columns and have the records go to the next row?
Here's my SQL table:
------------SQL TABLE -----------
id | product_name | product_type
0 | Lorem | Table
1 | Ipsum | Chair
2 | Dolor | Lamp
3 | Sit | Chair
This is what I would like.
Lorem | Ipsum | Dolor | Sit |
------------------------------------------------------------
id | 0 | 1 | 2 | 3 |
type | Table | Chair | Lamp | Chair |
Desired output:
<table>
<tr>
<td> </td>
<td>Lorem</td>
<td>Ipsum</td>
<td>Dolor</td>
<td>Sit</td>
</tr>
<tr>
<td>id</td>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>type</td>
<td>Table</td>
<td>Chair</td>
<td>Lamp</td>
<td>Chair</td>
</tr>
</table>
This is my code, but I know this is terribly wrong. I'm just stuck on how to make a new row for a field if that makes sense using while and for loops.
echo '<table><tr>';
$i=1;
while($rows = mysql_fetch_array($result)){
echo '<td><table><tr><th>'.$rows['product_name'].
'</th></tr><tr><td>'.$rows['product_id'].
'</td><td>'.$rows['product_type'].'</tr></table></td>';
if($i %2 == 0) {
echo '</tr>
<tr>'; }
}
echo'
</tr>
</table>';
You need to rotate your data.
You could use something like this (untested):
// build query
$query = "SELECT id, product_name, product_type FROM whatevertableyouhave";
// query the database
$result = mysql_query($query);
// cols we are interested in (from the SQL query)
$cols = array(
'id',
'product_name',
'product_type';
);
// initialize rotated result using cols
$rotated = array();
foreach($cols as $col) {
$rotated[$col] = array();
}
// fill rotated array
while(($row = mysql_fetch_assoc($result)) !== false) {
foreach($cols as $col) {
$rotated[$col][] = $row[$col];
}
}
// echo html
echo "<table>";
echo "<tr>";
foreach($cols as $col) {
echo "<th>{$col}</th>";
}
echo "</tr>";
foreach($rotated as $col => $values) {
echo "<tr>";
foreach($values as $value) {
echo "<td>" . htmlentities($value) . "</td>";
}
echo "</tr>";
}
echo "</table>";
try this
echo '<table>';
while($rows = mysql_fetch_array($result)){
echo '<tr><th>'.$rows['product_name'].
'</th></tr><tr><td>'.$rows['id'].
'</td></tr><tr><td>'.$rows['product_type'].
'</td></tr>';
}
echo' </table>';
Related
I want to export my code to excel however the header is also dynamic. Here is my code, i need assistance in exporting my data. This code below shows a dynamic table i showed in user view and needs to be exported. The view is:
"title: course/section"
"header: student id | student name | program | term | dynamic date 1 | Remarks (remarks why u are absent) including date 1 | date 2 | Remarks (remarks why u are absent) including date 2 | and so on.."
"table data: 20122222 |pinky webb |computer science | 3 | Absent | With medical certificate | present | no remark | present | no remark | late | no remark | and do on... "
"table data 2: 20122333 |Mane Sharpay|computer science | 3 | Absent | With medical certificate | present | no remark | Late | no remark | late | no remark | and so on... "
and so on...
basically, it shows the student and its attendance per date horizontally with a dynamic header of dates. sorry if im noob hehe but ill give a thumbs up i promise for ur effort
<?php
$query = "SELECT course_id, sections_id from current_att_view inner join professor_tbl on current_att_view.professor_id = professor_tbl.professor_id where professor_live_account = '".$_SESSION['username']."' group by course_id, sections_id";
$result1 = mysqli_query($link, $query);
while ($col1 = mysqli_fetch_array($result1))
{
$reslt;
echo '<h3 class="course-sect">'.$col1[0].'/'.$col1[1].'</h3>';
$qry = "Call Get_Attendance_Course_Section('".$_SESSION['username']."','".$col1[0]."','".$col1[1]."')";
$reslt = mysqli_query($link, $qry);
echo '<table class="table table-bordered">';
echo '<tr>';
if (!$reslt) {
printf("Error: %s\n", mysqli_error($link));
exit();
}
else{
while ($fieldinfo = mysqli_fetch_field($reslt)) {
if($fieldinfo->name != "Course" && $fieldinfo->name != "Section" && $fieldinfo->name != "Course Name" && $fieldinfo->name != "Schedule")
{
echo '<th>';
echo $fieldinfo->name;
echo '</th>';
}
}
echo '</tr>';
while ($rows = mysqli_fetch_array($reslt))
{
for ($i=0; $i < (count($rows)/2); $i++) {
if($i != 3 && $i != 4 && $i != 5 && $i != 6){
echo '<td>';
echo $rows[$i];
echo '</td>';
}
}
echo '</tr>';
}
echo '</table>';
mysqli_next_result($link);
}
}
// $reslt =mysqli_query($link, $qry);
?>
<input type=hidden name=date value='<?php echo date("F d, Y",strtotime($date));?>'>
<input type="hidden" name="outy" value="<?php echo $sql; ?>">
<input type="submit" name="export" value="Export" class="submit" />
i dont know how to explain it well but what i want is that i want to display the instrutors name and courses title in my subject table and the day&time of the subject and at first i can display the subjects with its instructor name and course title but when i display the day&time of it.it dont fit on my desired output..
here is my sample code:
//subjectClass.php
public function subjects(){
global $db;
$sql = "
SELECT s.*
, i.first_name
, i.mid_name
, i.last_name
, c.course_title
, d.sub_day
, d.start_time
, d.end_time
FROM subjects_tbl s
LEFT
JOIN instructors_tbl i
ON i.instructor_id = s.instructor_id
LEFT
JOIN courses_tbl c
ON c.course_id = s.course_id
LEFT
JOIN subject_day_tbl d
ON d.subject_id = s.subject_id;
";
$query = $db->query($sql);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$list[] = $row;
}
}else{
$list = NULL;
}
return $list;
}
//subjects.php
//include 'subjectsClass.php';
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th>Subject Code</th>
<th>Subject Title</th>
<th>Unit</th>
<th>Section</th>
<th>Course</th>
<th>Instructor</th>
<th>Day/Time</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$subjectsClass = new subjectsClass;
$subjects = $subjectsClass->subjects();
foreach ($subjects as $key => $value) {
?>
<tr>
<td><?php echo $value['subject_code']; ?></td>
<td><?php echo $value['subject_title']; ?></td>
<td><?php echo $value['unit']; ?></td>
<td><?php echo $value['section']; ?></td>
<td><?php echo $value['course_title']; ?></td>
<td><?php echo $value['first_name'] . " " . $value['mid_name'] . ". " . $value['last_name'] ; ?></td>
<td>
<?php echo $value['sub_day'] . " [" . $value['start_time'] . " - " . $value['end_time'] . "]<br />"; ?>
</td>
<td>Edit | Delete</td>
</tr>
<?php
}
?>
</tbody>
and here is the output:
Subject Code Subject Title Unit Section Course Instructor Day/Time
ITE 131 Security Issues and Principles 3 IT-R BSIT Darwin Paradela. Galudo Monday [07:30:00 - 09:00:00]
ITE 131 Security Issues and Principles 3 IT-R BSIT Darwin Paradela. Galudo Wednesday [08:30:00 - 10:00:00]
ITE 050 Database Management System 2 3 IT-R BSIT Ronnie Pitt. Cambangay Tuesday [07:00:00 - 08:30:00]
ITE 050 Database Management System 2 3 IT-R BSIT Ronnie Pitt. Cambangay Thursday [07:00:00 - 08:30:00]
my desired output is this one:
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
| Subject Code | Subject Title | Unit | Section | Course | Instructor | Day/Time |
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
| ITE 131 | Security Issues and Principles | 3 | IT-R | BSIT | Darwin Paradela. Galudo | Monday [07:30:00 - 09:00:00] |
| | | | | | | Wednesday [08:30:00 - 10:00:00] |
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
| ITE 050 | Database Management System 2 | 3 | IT-R | BSIT | Ronnie Pitt. Cambangay | Tuesday [07:00:00 - 08:30:00] |
| | | | | | | Thursday [07:00:00 - 08:30:00] |
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
my tables:
subjects_tbl
courses_tbl
instructors_tbl
subject_day_tbl
I hope I can help you.
Your issue seems to be the left join of subject_day_tbl. It is a one-to-many relationship (ie, there can be many records in subject_day_tbl for each record in subjects_tbl), and when you left join a one-to-many you'll get a duplicate of the "one" side for each row in the "many" side. The only way that you could do this in a single query is by using a subquery or group statement to concatenate the rows in the database engine... but that is really bad because you're mixing display with your data model.
While it is true in general that for performance one should avoid issuing too many queries to the database, premature optimization is the root of all evil. First, try to have clean, understandable code, then look for bottlenecks if you're having issues.
In this case, a second query is certainly best. This is how I would do it:
//subjectClass.php
protected function subject_days($subject_id)
{
// I don't know what type of object $db is it looks like ezSQL,
// but you get the idea
global $db;
$sql = "SELECT sub_day, start_time, end_time
FROM subject_day_tbl
WHERE subject_id = %s";
$query = $db->query($db->prepare($sql, $subject_id));
return ($query->num_rows > 0) ? $stmt->fetch_assoc() : array();
}
public function subjects()
{
global $db;
$sql = "SELECT s.*
, i.first_name
, i.mid_name
, i.last_name
, c.course_title
, d.sub_day
, d.start_time
, d.end_time
FROM subjects_tbl s
LEFT JOIN instructors_tbl i
ON i.instructor_id = s.instructor_id
LEFT JOIN courses_tbl c
ON c.course_id = s.course_id
";
$list = array();
$query = $db->query($sql);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$row['course_days'] = $this->subject_days($row['subject_id']);
$list[] = $row;
}
}
return empty($list) ? NULL : $list;
}
// subjects.php
$subjectsClass = new subjectsClass;
$subjects = $subjectsClass->subjects();
foreach ($subjects as $key => $value) {
?><tr>
<td><?php echo $value['subject_code']; ?></td>
<td><?php echo $value['subject_title']; ?></td>
<td><?php echo $value['unit']; ?></td>
<td><?php echo $value['section']; ?></td>
<td><?php echo $value['course_title']; ?></td>
<td><?php echo $value['first_name'] . " "
. $value['mid_name'] . ". "
. $value['last_name'] ; ?></td>
<td><?php foreach($value['course_days'] as $day) {
echo $value['sub_day'] . " [" . $value['start_time'] . " - " . $value['end_time'] . "]<br />";
}?></td>
<td>Edit | Delete</td>
</tr><?php
}
Also, not to be a pedant, but you should really be escaping your output before
echoing it, eg with htmlspecialchars.
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";
I have sql data result set having records as follows
id | name | hobbies
------------------------------------
1 | RAVI | PLAYING CRICKET
------------------------------------
1 | RAVI | LISTENING MUSIC
------------------------------------
2 | REENA | BADMINTON
------------------------------------
I am displaying this data in view by using html table.
Whereas my requirement is, I want to display as follows
id | name | hobbies
------------------------------------
1 | RAVI | PLAYING CRICKET
| | LISTENING MUSIC
------------------------------------
2 | REENA | BADMINTON
------------------------------------
meaning I want to display records with id 1 into one <td>
I am using php foreach loop to display result.
How can I achieve this?
My current code is as follows and is results into same as my first table whereas I want my view as in the second table.
<table class="table table-striped">
<tr >
<th>ID</th>
<th>Name</th>
<th>Hobbies</th>
</tr>
foreach($result as $row)
{
echo "<tr>
<td>".$row->id."</td>
<td>". $row->name."</td>
<td>". $row->hobbies."</td>
</tr>";
}
</table>
A quick way to approach this would be to modify your MySQL query to use GROUP_CONCAT(hobbies) to group all of a user's hobbies together. The query would look something like:
SELECT
id, name, GROUP_CONCAT(hobbies) AS hobbies
FROM
your_table
GROUP BY
id
This will group all of a user's hobbies in a comma-delimited list. To display it, you can use PHP's explode() and iterate over that:
foreach ($results as $row) {
echo '<tr>';
echo '<td>' . $row->id . '</td>';
echo '<td>' . $row->name . '</td>';
echo '<td>';
$hobbies = explode(',', $row->hobbies);
foreach ($hobbies as $hobby) {
// output each hobby and decorate/separate them however you'd like
echo $hobby . '<br />';
}
echo '</td>';
echo '</tr>';
}
If you don't want the inner loop (or the ending <br /> that will pad the hobbies), you can use str_replace() instead:
echo str_replace(',', '<br />', $result['hobbies']);
This post may help you: Concatenate many rows into a single text string?
Just replace the , with </br>.
in each iteration, you must save the last ID, in the next iteration you must check it whether its value has been changed or not. Something like this:
$res = $this->db->query('.....');
$last_ID = '';
foreach ($res->result() as $row) {
if ($row->id != $last_ID) {
if (strlen($last_ID)>0) echo '</td></tr>';
echo '<tr>';
echo '<td>$row->id</td>';
echo '<td>$row->name</td>';
echo '<td>$row->hobbies';
} else {
echo '<br />'.$row->hobbies;
}
$last_ID = $row->id;
}
if ($res->num_rows() > 0) echo '</td></tr>';
Supposing you have your row in $row var and the ID is $row["ID"]
?>
<td id="<php echo $row["id"]; ?>">
<?php echo $row["id"]; ?>
</td>
<?php
I have this table:
img id | img_path | listing_assoc_id|
----------------------------------------
11 |img/img1.jpg | 12 |
12 |img/img2.jpg | 12 |
13 |img/img3.jpg | 12 |
14 |img/img4.jpg | 12 |
15 |img/img5.jpg | 12 |
16 |img/img6.jpg | 12 |
18 |img/img7.jpg | 12 |
21 |img/img8.jpg | 12 |
22 |img/img9.jpg | 12 |
23 |img/img10.jpg| 12 |
24 |img/img11.jpg| 12 |
And I want to display it into a table in html
like this maximum of 5 images per row. I have been fiddling with different loops in combination of different loops like above for a couple hours but haven't found one that works like I need. They are either displaying the same images across the entire row or are messed up in some other way. Obviously need to use tr & td elements to format table correctly.
What I need:
<tr>
<td>img1</td> <td>img2</td> <td>img3</td> <td>img4</td> <td>img5</td>
</tr>
<tr>
<td>img6</td> <td>img7</td> <td>img8</td> <td>img9</td> <td>img10</td>
</tr>
<tr>
<td>img11</td>
</tr>
Some of the code that doesn't work:
$query = "SELECT * FROM listings_gallery WHERE listing_assoc_id = " 12 " ORDER BY img_id ASC";
$image_set = mysqli_query($connection, $query);
echo '<tr>';
while($img = mysqli_fetch_assoc($image_set)){
while($img['img_id'] < 5){
echo "<td><img src='" . $img['img_path'] . "'></td>";
}
echo '<tr>';
}
I wouldn't actually depend on the image ID. You could use % 5 to do this, but the IDs may be out of order, etc. Instead, you can just fetch everything into an array and use array_chunk
$img = array();
while ($img = mysqli_fetch_assoc($image_set)) {
$imgs[] = $img;
}
foreach (array_chunk($imgs, 5) as $img_chunk) {
echo "<tr>";
foreach ($img_chunk as $img) {
echo "<td>$img</td>";
}
echo "</tr>";
}
This is probably about as simple as it gets but it's not as memory efficient as could be. You could also maintain your own counter and check % 5 for that to break out of the inner loop.
$images_rows = mysqli_query($connection, $query);
$images = array();
while ($image = mysqli_fetch_assoc($images_rows)) {
$images[] = $image;
}
echo '<table><tr>';
$ct = 0;
$ctt = 0;
$size = sizeOf($images) - 1;
foreach($images as $image){
if($ct == 5) {
echo '<tr>';
$ct = 0;
}
echo "<td><img src='" . $image['img_path'] . "'></td>";
$ct++;
$ctt++;
echo ($ct == 5 && $ctt != $size) ? '</tr>': '';
}
echo '</tr></table>'