Mysql fetch array, table results - php

i'm pretty new to this and not sure how should i do it,
I've got a database with a column called "names"
how can i make it display in so?
<tr>
<td width="270px">Henry</td>
<td width="270px">Jeffrey</td>
<td width="270px">Hansel</td>
</tr>
<tr>
<td width="270px">Michelle</td>
<td width="270px">Jackson</td>
<td width="270px">Ivan</td>
</tr>
I only know how i should do it if the records goes one after another vertically.
$result = mysql_query('SELECT * FROM member');
while($row = mysql_fetch_array($result))
{
echo'
<tr>
<td width="270px">'.$row['names'].'</td>
<td width="270px">Jeffrey</td>
<td width="270px">Hansel</td>
</tr>';
Kinda stucked here...
Sorry i forgot to put this.
what i want is that it should loop the tags along. So i can have a 3 column table with infinite rows.
what bout this one? What if i want this to loop instead?
<tr>
<td><img src="images/ava/A.png" /></td>
<td>A</td>
<td width="2px" rowspan="3"></td>
<td><img src="images/ava/B.png" /></td>
<td>B</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
</tr>

$row will update on each iteration of the loop:
$result = mysql_query('SELECT * FROM member');
echo '<tr>';
for($i = 0; $row = mysql_fetch_array($result); $i = ($i+1)%3){
echo '<td width="270px">'.$row['names'].'</td>';
if($i == 2)
echo '</tr><tr>';
}
echo '</tr>';

$result = mysql_query('SELECT * FROM member');
echo'<tr>'
while($row = mysql_fetch_array($result))
{
echo '<td width="270px">'.$row['names'].'</td>';
}
echo '</tr>';

$result = mysql_query('SELECT * FROM member');
echo '<tr>;
while($row = mysql_fetch_array($result))
{
echo '<td width="270px">'.$row['names'].'</td>';
}
echo '</tr>';

Lets say you have an array of the names called $names, then you could do what you wanted with code that looks something like this:
<tr>
<?php
foreach($names as $name) {
print "<td>$name</td>";
}
?>
</tr>
That would put all the names on the same row.
In order to start a new row say, every 3 names, you could put an if statement in the for loop like this:
// assume we have these variables available.
$row_number;
$max_cols = 3;
// this goes at the top of the foreach
if($row_number % $max_cols == 0) {
print '</tr><tr>';
}

You know accomplish this by assigning the row count before you start the variable and few flags to know initialized loop or started/ended loop.
$i = 1;
$initFlag = false;
$flag = "closed";
while($row = mysql_fetch_array($result)) {
if($i%3 == 0) $initFlag = false;
if($flag == "closed" && ($i == 1 || $i % 3 == 1)) {
echo "<tr>"; $flag = "started"; $initFlag = true;
}
echo '<td width="270px">'.$row['names'].'</td>';
if(!initFlag && $flag == "started" && $i % 3 ==0) {
echo "</tr>"; $flag = "closed";
}
$i++;
}

So most of these answers are going for the kludge. First, if all you want is the name in your resultset, then only ask for it. So rather than going with:
$result = mysql_query('SELECT * FROM member');
Instead go with:
$result = mysql_query('SELECT names FROM member');
Also, everyone seems to be ignoring the three column request, and that can be satisfied using a modulo to tell when to break the rows. We'll do a little magic to make sure you always close the row tag.
$row_count = 0;
while($row = mysql_fetch_array($result))
{
if( $row_count % 3 == 0 )
{
echo '<tr>';
}
echo '<td width="270px">'.$row['names'].'</td>';
if( $row_count % 3 == 0 )
{
echo '</tr>';
}
$row_count++;
}
I don't want to get too picky about your schema, but if you have a choice, it's better to name the table a plural like members rather than member, since you have a collection of rows, each one representing one 'member'. And unless your members have multiple names that column could probably best be called 'name' instead.

Related

Filling table in a specific way with sql data using loops

I want to put data from the following database table in a html table in a specific way.
Below is my php code:
echo "<table style='border:2px solid black;width:100%;'>";
foreach ($results as $key => $value) {
for ($i = 1; $i < 4; $i++) { // 3 + 1 = 4 (itération sur la valeur de $value['ligne'])
if ($i == $value['ligne']) {
echo "<tr>";
for ($j = 1; $j < 4; $j++) { // itération sur la valeur de $value['colonne']
//if ($j == $value['colonne'] ) {
echo "<td style='padding:1em;border:1px solid black;'>".$value['contenu']."</td>";
//}
}
echo "</tr>";
}
}
}
echo "</table>";
And here is the output that i'm having:
What I want to achieve is having "colonne1" only in the column 1 of the table; "colonne2" only in column 2, etc. In the same way, "Ligne1" should appear only in row 1; "Ligne2" in row 2, which is what i've been able to do. Any idea? Thanks, in advance.
You can use a two dimensional array to achieve the object seeing you’re looking for.
First, build a data structure from the database results.
// assuming you’ve retrieved table into $results
$table =array();
foreach($results as $v) {
$row = $v[‘ligne’];
$col = $v[‘colonne’];
$content = $v[‘contenue’];
$table[$row][$col] = $content;
}
// build html table
?>
Then you can print it out in the view:
<table>
<?php foreach($table as $row_array): ?>
<tr>
<?php foreach($row_array as $col): ?>
<td><?= $col ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

Change on every other row

I have problem with that the first row misses a <tr> and then there is one line and then there is a </tr> and then it works perfect with one <tr> and two lines and </tr> and so on. How to change the code to make that work?
Any ideas to use "div" instead of "table"?
<table width="300" border="0" cellspacing="2">
<tbody>
<?
$query = mysql_query("SELECT * FROM pages ORDER BY id ASC");
while($r = mysql_fetch_array($query))
{
if(++$s % 2 == 0) { echo '<tr>'."\r\n"; }
echo '<td> · '.$r['domain'].' </td>'."\r\n";
if(++$i % 2 != 0) { echo '</tr>'."\r\n"; }
}
?>
</tbody>
</table>
Use $s++ instead of ++$s, so you test the value before you increment it. And there's no need to use a separate $i variable, you can just use the same $s variable without incrementing it.
$s = 0;
while ($r = mysql_fetch_array($query)) {
if ($s++ % 2 == 0) {
echo "<tr>\r\n";
}
echo '<td> · '.$r['domain'].' </td>'."\r\n";
if ($s % 2 == 0) {
echo "</tr>\r\n";
}
}
// If we ended loop without closing the row, do it now
if ($s % 2 == 0) {
echo "</tr>\r\n";
}
Sounds like you're trying to build a 2-column table? You don't need two counters for that, one will do:
$cells = 0;
while(...) {
if (($cells % 2) == 0) {
echo '<tr>'; // start a new row for cells 0, 2, 4, etc...
}
echo '<td> ....';
if (($cells % 2) == 1) {
echo '</tr>'; // close the row after outputting cells 1,3,5,etc...
}
$cells++;
}

PHP - put the student name and grade into suitable skill name

(1) class
(2) studentmark
(3) skill
PHP code:
<?php
//DB CONNECTION
//---(1)Get skillname---
$q = "SELECT skillName FROM skill ORDER BY skillName asc";
$r = mysqli_query($dbc, $q);
$num_rows = mysqli_num_rows($r);
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$skills[] = $row['skillName'];
}
//---(2)Get classname---
$q1 = "SELECT className FROM class";
$r1 = mysqli_query($dbc, $q1);
$num_rows1 = mysqli_num_rows($r1);
while($row1 = mysqli_fetch_array($r1, MYSQLI_ASSOC))
{
$className[] = $row1['className'];
}
//---(3)Create table---
echo '<table border="1" style="border-collapse: collapse; text-align: center">';
echo '<tr>';
for($a = 0; $a < $num_rows; $a++)
{
echo '<th colspan="2">'.$skillName[$a].'</th>';
}
echo '</tr>';
for($b = 0; $b < $num_rows; $b++)
{
echo '<th>Student Name</th>';
echo '<th>Grade</th>';
}
echo '</tr>';
//---(4)Get student name and grade---
for($s = 0; $c < $num_rows1; $c++)
{
$q2 = "SELECT GROUP_CONCAT(sm.studentName) as studentName,
GROUP_CONCAT(sm.studentGrade) as studentGrade,
s.skillName
FROM studentmark sm
LEFT JOIN skill s ON sm.skillID = s.skillID
WHERE sm.className = '".$className[$c]."'
GROUP BY s.skillID";
$r2 = mysqli_query($dbc, $q2);
$num_rows2 = mysqli_num_rows($r2);
$value = array();
while($row2 = mysqli_fetch_array($r2, MYSQLI_ASSOC))
{
$value[] = $row2;
}
echo '<tr>';
for($d = 0; $d < $num_rows2; $d++)
{
echo '<td>'.$value[$d]['studentName'].'</td>';
echo '<td>'.$value[$d]['studentGrade'].'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
From above code, my output is below:
I am almost finished. I can show the student name and grade in 1 row.
Now, the last thing I want to do is put them into suitable skill name like below:
I want to compare the $skills and s.skillname on $q2.
Below is my logic:
if($value[X]['skillName'] == $skills[X])
{
//put student name and grade inside
}
else
{
//empty cell
}
But I don't know where should I open for loop and put my logic in (4). Can someone help me?
So I'm definitely messing up your nice clean code for the sake of not looping through the data multiple times. I also display the classnames cause that seems like useful info.
I changed some variable names cause I found it easier to remember what each variable was for. Also, note how the student info query is only executed once. Normaly (read: I can't think of a reason why you wouldn't but I'm CMA), you want to minimize the number of times you query the database
The code below will replace the entire script you posted.
<?php
//DB CONNECTION
$dbc = // magic connection sauce you already have
// get skills and stash how many there are
$q_class = "SELECT skillName FROM skill ORDER BY skillName asc";
$r_class = mysqli_query($dbc, $q_class);
$num_skills = mysqli_num_rows($r_class);
// start table code so that we can echo the skillname headers
echo '
<table border="1" style="border-collapse: collapse; text-align: center">
<thead>
<tr>
<th rowspan=2>Classes</th>';//header for class name column
$header = array();
while($row = mysqli_fetch_array($r_class, MYSQLI_ASSOC))
{
$skills[] = $row['skillName'];
// store both thead rows at the same time so that we can echo them out properly later
$header['first'][] = '
<th colspan="2">' . $row['skillName'] . '</th>';
$header['second'][] = '
<th>Student Name</th>
<th>Grade</th>';
}
echo '
' . implode($header['first']) . '
</tr>
<tr>' . implode($header['second']) . '
</tr>';
// clean-up
mysqli_free_result($r_class);
// get class names and stash how many there are
$classes = array();
$query_class = "SELECT className FROM class";
$r_class = mysqli_query($dbc, $query_class);
$num_classes = mysqli_num_rows($r_class);
while($row = mysqli_fetch_array($r_class, MYSQLI_ASSOC))
{
$classes[] = $row['className'];
}
// clean-up
mysqli_free_result($r_class);
echo '
</thead>
<tbody>';
// pull query out of loop so that you'll only have to execute it once.
$studentInfoQuery = "
SELECT
GROUP_CONCAT(sm.studentName) as studentName,
GROUP_CONCAT(sm.studentGrade) as studentGrade,
s.skillName,
sm.className
FROM studentmark sm
LEFT JOIN skill s ON sm.skillID = s.skillID
GROUP BY sm.className,s.skillID";
$r_students = mysqli_query($dbc,$studentInfoQuery);
$num_studentRows = mysqli_num_rows($r_students);
$studentRows = array();
while($row = mysqli_fetch_array($r_students, MYSQLI_ASSOC)) {
// with our query, we only find 1 cell-pair per skill per class
$studentRows[$row['skillName']][$row['className']] = '
<td>' . $row['studentName'] . '</td>
<td>' . $row['studentGrade'] . '</td>';
}
// everybody do their share! // actually, more clean-up
mysqli_free_result($r_students);
for($j = 0; $j < $num_classes; $j++) {
echo "
<tr>
<th>" . $classes[$j] . "</th>";
for($i = 0; $i < $num_skills; $i++) {
// always echo out a cell, even if we have student info for it
// example: if(isset($studentRows['Listening']['1A'])) echo it out else echo cell
if(isset($studentRows[$skills[$i]][$classes[$j]]))
echo $studentRows[$skills[$i]][$classes[$j]];
else
echo "
<td colspan=2>No skill-class-student value</td>";
}
echo "
</tr>";
}
echo '
</tbody>
</table>';
?>
Results:
You are doing fine(although the things can be optimized) up to the last loop of step 4 in your design.
The problem you face right there is that you have a set of results which represent each class in it's rows. Now you need to spread them out in to skill table, importantly, without leaving vertical gaps.
The solution is to do it in a two dimension array in the memory and then create the table from it - because each cell in the memory is easily addressable than cells in an html table.
Memory table is going to be something like this:
|Skill 1 | Skill 2 | Skill3|
|stdnt 1 |stdnt 2,3|stdnt 4|
| | |stdnt 5|
Please note how I have used array_search to get the index of a particular skill and use it in array_push to insert the student in to the correct child array. Then I have just translated it in to an HTML table
I'm replacing your last loop with the following code:
//This is our memory table. Let's create it and add number of child arrays
//equal to number of skills.
$memTable = array();
for ($i = 0; $i <= sizeOf($skills) - 1; $i++) {
$memTable[$i] = array();
}
//Lets spread out your student information in to this 2d array now
foreach ($value as $student) {
//Get the index of the skill
$skillIndex = array_search($student['skillName'], $skills);
//Now go to appropriate child array and insert your student there
array_push($memTable[$skillIndex], $student);
};
//Lets create the table now
$emptyCount = 0;
$currentRow = 0;
//Do until all the skill arrays are empty for a row
while ($emptyCount < 3) {
echo "<tr>";
$emptyCount = 0;
foreach ($memTable as $skillLevel) {
if (sizeof($skillLevel) - 1 < $currentRow) {
$emptyCount ++;
echo "<td>&nbsp</td>";
echo "<td>&nbsp</td>";
}
else {
echo "<td>" . $skillLevel[$currentRow]['studentGrade'] . "</td>";
echo "<td>" . $skillLevel[$currentRow]['studentGrade'] . "</td>";
}
}
$currentRow++;
echo "</tr>";
};
Please note that the skills will be rendered in the table according to the order they are in the $skills array. Please ask me questions if there is any place that is not clear to you. You might need to adjust some String names to adopt in to your code.
UPDATE
while ($emptyCount < sizeof($skills)) is more accurate.

Table designing in while loop

I want to show 4 images from database in a table (2*2) I know how to do that. But I have also special condition (if there are less picture than 4, it will show default pictures to show 4 images totally)
I manage this in a while loop. If there are 4 images there is no problem, it works as I want but when there are fewer images (which means default images will be completed 4 images in total) it doesn't work. I can't figure out how to do that.
Any help?
<table>
<tr>
<?php
$todisplay = 4;
$query = mysql_query("select * from Images where Country_ID=$co_id LIMIT 0,4;");
while ($row = mysql_fetch_array($query)) {
$x++;
echo "<td><img src='".$row['I1_Th'] . "'/></td>";
$displayed_number++;
if ($x % 2==0) {
echo "</tr><tr>";}
}
echo str_repeat("<td>
<img src='images/png/defthumb.png'> </td>", $todisplay-$displayed_number);
?>
</tr></table>
You were not far from it - simply create another loop that does the same thing, but with the default image instead. Also, the $displayed_number seems to hold the same value as $x, so I deleted it.
<table>
<tr>
<?php
$todisplay = 4;
$query = mysql_query("select * from Images where Country_ID=$co_id LIMIT 0,4;");
$x = 0;
while ($row = mysql_fetch_array($query)) {
$x++;
echo "<td><img src='".$row['I1_Th'] . "'/></td>";
if ($x % 2==0) {
echo "</tr><tr>";}
}
while ( $x < $todisplay) {
$x++;
echo "<td><img src='images/png/defthumb.png'/></td>";
if ($x % 2==0) {
echo "</tr><tr>";}
}
?>
</tr></table>
Instead of looping over the rows returned by your query, why not just loop four times and attempt to fetch a row instead?
<table>
<tr>
<?php
$tablerows = 2;
$query = mysql_query("select * from Images where Country_ID=$co_id LIMIT " + ($tablerows * 2) + ";");
for ($x = 1; $x <= ($tablerows * 2); $x++) {
if ($row = mysql_fetch_array($query)) {
echo "<td><img src='".$row['I1_Th'] . "'/></td>";
} else {
echo "<td><img src='images/png/defthumb.png'></td>";
}
if ($x % 2==0 && $x != $tablerows * 2) {
echo "</tr><tr>";}
}
?>
</tr></table>

Render SQL query results as an HTML table

I need help rendering data in PHP:
I want to use the results of a SQL query to populate a table, displaying images in a 4-column grid. Here's what I've written so far:
$result = mysql_query("SELECT * FROM gallery ORDER BY id ASC ");
while($row = mysql_fetch_array($result))
{
echo "<td align=\"center\" ><img src=\"upload_gallery/thumbnail/sml_".$row['image_name']."\" width=\"200\" height=\"170\" /></td>";
}
<table><tr>
<?$result = mysql_query("SELECT * FROM gallery ORDER BY id ASC ");
$result =mysql_fetch_array($result)
$count=0;
for($row =0; $row<count($result); $row++)
{
$count++
if($count==4){
echo '</tr><tr>';
$count=0;
}
echo "<td align=\"center\" ><img src=\"upload_gallery/thumbnail/sml_".$row['image_name']."\" width=\"200\" height=\"170\" /></td>";
}
?>
</tr>
</table>
You can do a for loop as was suggested by Frederick:
$num_rows = mysql_num_rows($result);
for($i = 0; $i < $num_rows; $i++)
{
// Check if beginning of row
if($i % 4 == 0)
{
//If not the first row, end the last row first
if($i > 0)
{
echo "</tr>";
}
echo "<tr>";
}
$row = mysql_fetch_assoc($result);
//Output each individual image
echo "<td> {*EACH IMAGE code*}</td>";
}
That should give you the idea.
Try this one:
$arr =array("Test1","Test2","Test3","Test4","Test5","Test6","Test7","Test8","Test9","Test10");
echo "<table><tr>";
for($i = 1 ; $i <= count($arr) ; $i++)
{
echo"<td>".$arr[$i-1]."</td>";
$last = $i % 4 == 0? "<tr/><tr>":"";
echo $last;
}
echo "</table>";
Try this, hope it works for you,
while($row = mysql_fetch_array($result))
{
$data[]= $row['image_name'];## Pass the image data to new array
}
$ImagePerRow = 4;### Set the value of image per table row
echo "<table border='1'><tr>";
foreach($data as $key => $ImageName)
{
if(($key+1) == $ImagePerRow)## if key index+1 is equal to ImagePerRow
{
echo "<td align=\"center\" ><img src=\"upload_gallery/thumbnail/sml_".$ImageName."\" width=\"200\" height=\"170\" /></td></tr><tr>";## then close the table row and start a new table row
$ImagePerRow+=4;### Add a value of 4 in order to increment the imageperRow value on the next loop
}else{
echo "<td align=\"center\" >".$ImageName."</td>";### else echo the normal table data
}
}
echo "</tr></table>";

Categories