Filling table in a specific way with sql data using loops - php

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>

Related

how can show a html table row by row using php

this is my code to display a html table using php :
echo "<table border='1'>";
for ($r =0; $r < $rows; $r++){
echo'<tr>';
echo "<th> Etat".$r."</th>";
for ($c = 0; $c < $rows; $c++){
echo '<td><input type="checkbox" name="'.$r.''.$c.'" placeholder="nb d etat" /></td>';
}
if ($c==$rows) {
ECHO '<td><input type="number" name="'.$r.''.$c.'" placeholder="etat" /></td>';
}
echo '</tr>'; // close tr tag her
}
echo "</table>";
and this is the php file to recuperate data
foreach ($p as $k => $v) {
if ($v=="on") {
# code...
$a= "X$k \n";
echo $a;
}
else {
$b="$v \n";
echo $b;
}
}
and this is the result :
X00
X02
12
X10
X11
21
X22
17
the objective is :
if the checkbox checked recupere the keys of the same row like this :
(X00+X01+X02 .......etc)
follows recupere the value (input in the last column of the table ) ex:12
finally a want to traduce each row like this :
12(X00+X02)
21(X10+X11)
17(X22)
i want just to display this table like this
please help me to do this
and thanks in advance

Split query results in 2 div's

i have this php mysql query
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$pro = mysql_fetch_assoc($product);
?>
Now that query will return 6 products from database and what i want to do is echo 3 products inside a <div> and the other 3 products inside another <div> like this
<div class="first-3>
///Here i want to echo 3 products from the query from 1-3
<?php echo $pro['title']; ?>
</div>
<div class="second-3>
///Here i want to echo the rest 3 products of the query from 4-6
<?php echo $pro['title']; ?>
</div>
<?php
$num = 6;
$product = mysql_query('SELECT * FROM products LIMIT $num');
$firstDiv = "";
$secondDiv = "";
$i = 0;
while ($pro = mysql_fetch_assoc($product)) {
if ($i < ($num /2)) {
$firstDiv .= $pro['title'];
}
else {
$secondDiv .= $pro['title'];
}
$i++;
}
?>
And:
<div class="first-3>
<?php $firstDiv ?>
</div>
<div class="second-3>
<?php $secondDiv ?>
</div>
Iterate and output the values.
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$i = 1;
echo '<div class="first-3">';
while ( $pro = mysql_fetch_assoc($product) ) {
if ($i === 3) {
echo '</div><div class="second-3">';
}
echo $pro['title'];
$i++;
}
echo '</div>';
?>
Note that it's not safe to use mysql_query, you should be using mysqli or preferrably PDO.
mysql_fetch_assoc is used to retrieve a row in the resultset.
Doc: http://php.net/manual/es/function.mysql-fetch-assoc.php
A loop is required to iterate on each row.
A very simple example:
// Get a collection of 6 results
$products = mysql_query('SELECT * FROM products LIMIT 6 ');
// iterate over the 6 results
$i=0;
echo '<div class="first-3>';
while ($pro = mysql_fetch_assoc($products)) {
$i++;
// Print an item
echo $pro["title"];
// If 3 items are printed end first div and start second div
if($i==3){
echo '</div><div class="second-3">';
}
}
echo '</div>';
// Free the collection resources
mysql_free_result($products);
Just set up a counter to divide in groups of 3:
$count = 0;
while (...)
{
// your code
$count++;
if ( ($count % 3) === 0 )
{
echo '</div><div class="...">';
}
}
Please note that the mysql_* functions are deprecated and you should switch to PDO or mysqli.
$product = mysqli_query($conn, 'SELECT * FROM products LIMIT 6 ');
$results = array();
while($pro = mysqli_fetch_assoc($product)) {
$results[] = $pro;
}
echo '<div class="first-3">';
for($i = 0; $i < 3; $i++) {
echo $results[$i]['title'];
}
echo '</div><div class="second-3">';
for($i = 3; $i < 6; $i++) {
echo $results[$i]['title'];
}
echo '</div>';
Everytime you get the multiple of 3, ($k % 3 == 0) you will increment the flag variable, you can do then some conditions with the variable flag, i used here iterators because the hasNext() beauty.
Example
$pro = array(1, 2, 3, 4, 5, 6);
$flag = 0;
$pro = new CachingIterator(new ArrayIterator($pro));
foreach ($pro as $k => $v) {
// if multiples 3
if ($k % 3 == 0) {
$flag++;
if ($flag == 1) {
echo '<div class="first-3" style="border:1px solid black;margin-bottom:10px;">';
} else if ($flag == 2) {
echo '</div>'; // Closes the first div
echo '<div class="second-3" style="border:1px solid red">';
}else{ // if you have more than 6
echo '</div>';
}
}
// insert Data
echo $v . '<br/>';
if (!$pro->hasNext())
echo '</div>'; // if there is no more closes the div
}

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>";

table + foreach - new column?

<?php
$values = array();
for($i=0;$i<100;$i++){
$values[$i] = "aaa" . $i;
} ?>
<table>
<?php
foreach ($values as $i => $val) {
echo "<tr><td>" . $val . "</td> </tr>";
} ?>
</table>
this generated me:
aaa1
aaa2
...
aaa50
...
aaa90
...
aaa100
how can I make two column?
aaa1 aaa50
aaa2 ....
... aaa90
aaa50 aaa100
but no:
aaa1 aaa2
aaa3 aaa4
... ....
aaa99 aaa100
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$temp = sqlArr("SELECT value FROM table");
$data = array();
for($i=0;$i<50;$i++){
$data[] = array($temp[$i],$temp[$i+50]);
}
unset($temp);
a template
<table border='1'>
<? foreach ($data as $i => $row): ?>
<tr>
<? foreach ($row as $cell): ?>
<td><?=$cell?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
Try if this works for you. Regardless of the format of the items contained in $values, it should print the array the way you want.
<?php
$size = count($values);
$halfSize = intval(ceil($size / 2));
for ($i = 0; $i < $halfSize; $i++)
{
$j = $i + $halfSize;
echo "<tr><td>" . $values[$i] . "</td>";
// If $size is odd, $halfSize is rounded up. This means that if we have
// 3 elements, it will try to access to $values[3], since $halfSize would
// be 2. The last second column element should be blank in this case.
// So, if $halfSize is odd, and $i is the last element, don't print an
// additional table cell.
if (!($i == $halfSize - 1 && $size % 2 == 1))
echo "<td>" . $values[$j] . "</td>";
echo "</tr>";
}
?>
The way that I would do this is to create two separate tables (each one column wide) and then include both of them in a single, two-columned table:
<?php
$list=array('a','b','c','d','e','f');
$midpoint=floor(count($list)/2);
$tableHeader='<table width="100%">';
$tableFooter='</table>';
$leftTable=$tableHeader;
$rightTable=$tableHeader;
for ($c=0; $c<$midpoint; $c++)
{
$leftTable.='<tr><td width="100%">'.$list[$c].'</td></tr>';
}
$leftTable.=$tableFooter;
for ($c=$midpoint; $c<count($list); $c++)
{
$rightTable.='<tr><td width="100%">'.$list[$c].'</td></tr>';
}
$rightTable.=$tableFooter;
$mainTable='<table><tr><td width="50%">'.$leftTable.'</td><td width="50%">'.$rightTable.'</td></tr></table>';
echo $mainTable;
?>
Add some CSS to remove padding around the sub-tables and borders etc and you should be good to go.
Since you already numbered it, just abstract it down:
a1 a51
a2 a52
...
a49 a99
a50 a100
is exactly the same as
a1 a1+50
a2 a2+50
...
a50 a50+50
This makes you having the following code:
echo "<table>";
for($i=1; $i<=50; $i++) {
echo "<tr><td>" . $i . "</td><td>" . ($i+50) . "</td></tr>";
}
echo "</table>";
Note: This requires you to let the table be generated this way. If it's actually not numbered like that, you would have to figure out another way to generate the abstract table in my listing 2 (just think about the index the entries have in relation to their left neighbor).

Mysql fetch array, table results

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.

Categories