i want to display values from a database (a list of categories) into a table that has 2 columns and x number of rows.
I want my web page to display like this:
Apes Cats
Apples Cherries
Bats Tigers
Berries Zebras
Instead of
Apes Apples
Bats Bears
Cats Cherries
Tigers Zebras
Here is my code so far:
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
while ($category = mysqli_fetch_array($data)) {
?>
<tr>
<td><?php echo $category['cat_name'] ?></td>
</tr>
<?php } ?>
</table>
Here's the basic idea:
You get the count of the data via num_rows
Divide by two.
Now, the result of your division will be the number of rows.
Output a loop echoing value for row x and x+ num rows. For example the output of line 1 would be :
<tr><td>$row[val1][data]</td><td>$row[val5][data]</td></tr>
So, your loop would ultimately output:
val 1 | val 5
val 2 | val 6
val 3 | val 7
val 4 | val 8
The loop should end when your incrementing variable = num_rows. Should be pretty straightforward from there. Good luck.
Try this (haven't tested it though):
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
# Calculate total rows and half rows, rounded up
$full_row_count = mysqli_num_rows($data);
$half_row_count = ceil($full_row_count / 2);
$i = 0;
while ($i <= $half_row_count) {
# Set the result pointer for first column ...
mysqli_data_seek($data, $i);
$category_1 = mysqli_fetch_array($data);
# ... then calculate the offset for the second column ...
$col_2_offset = $i + $half_row_count;
# .. and make sure it's not larger than total rows - 1
if ($col_2_offset <= $full_row_count - 1) {
mysqli_data_seek($data, $col_2_offset);
$category_2 = mysqli_fetch_array($data);
} else {
$category_2 = array('cat_name' => '');
}
?>
<tr>
<td><?php echo $category_1['cat_name'] ?></td>
<td><?php echo $category_2['cat_name'] ?></td>
</tr>
<?php
$i++;
}
?>
</table>
Hope this helps !
You can add an another variable say, $i, to the loop and just increment this through as follows:
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$i=1;
while ($category = $data->fetch_row()) {
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $category[1] ?></td>
</tr>
<?php
$i++;
} ?>
</table>
EDIT: Updated to fetch row data for each result and assume that cat_name is the second item in the array i.e. $category[1].
If it doesn't have to be a table and your fine with browsers that support CSS 3, then you can use CSS columns:
http://jsfiddle.net/QKuDL/
Otherwise you'll need to sort the results first (untested - PHP is not my strong suit):
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$col_count = 2;
$max_items_per_col = ceil( mysqli_num_rows ( $data ) / $col_count );
$cols = array(array());
$col = 0;
while ($category = mysqli_fetch_array($data)) {
if (count($cols[$col]) >= $max_items_per_col) {
$col++;
}
$cols[$col][] = $category['cat_name'];
}
?>
<table> <!-- all of those attributes should be CSS instead -->
<?php for ($i = 0; $i < $max_items_per_col; $i++) { ?>
<tr>
<?php foreach ($cols as $col) { ?>
<td><?php if(isset($col[$i])) echo $col[$i]; ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$midpoint = ceil($data->num_rows / 2);
$i=0;
while ($category = $data->fetch_array()) {
if ($i < $midpoint)
$left[$i] = "<td>" . $category['cat_name'] . "</td>";
else
$right[$i - $midpoint] = "<td>" . $category['cat_name'] . "</td>";
$i++;
}
print "<table>";
for ($j=0; $j < $i; $j++)
{
print "<tr>" . $left[$j];
if (array_key_exists($j, $right)) print $right[$j];
print "</tr>";
}
print "</table>";
Related
I currently can print 8 records in one column, I am trying to print 16 records in 2 columns of 8 or 24 in 3 columns of 8. After several months of trying I have to admit it baffles me. Any help or guidance would be greatly appreciated. My code below gives me the first column of 8 perfectly, but after that I am stuck
$result1 = $db->prepare("SELECT * FROM table WHERE id='100' ORDER BY id ASC LIMIT 8 ");
$result1->execute();
print("");
$count = $result1->rowCount();
print("");
for($i=0; $row = $result1->fetch(); $i++) {
?>
<body topmargin="0">
<table border="0">
<tr>
<td>
<font size="5">ID:<?php echo $row['id']; ?></font><br>
<font size="5"><?php echo $row['field1']; ?></font><br>
<font size="5">Field1<?php echo $row['field2']; ?></font><br>
<font size="4">Field2<?php echo $row['field3']; ?></font><br>
<font size="3">Field3<?php echo $row['field4']; ?></font><br>
</td>
</tr>
<?php
}
?>
I would approach this by making a loop to output a table with a desired column count.
Within that you will need to iterate a number of rows, and then inside that loop, write out the table entry for each of the columns.
If your data doesn't exactly fill columns x rows then you'll get some blank items of course.
$rows = ceil($count / $columns)
for ($r = 0; $r < $rows; $r++) {
echo "<tr>";
for ($c = 0; $c < $columns; $c++) {
$value = $result1->getNext() ?? '';
echo "<td>{$value}</td>";
}
echo "</tr>";
}
The getNext() here is up to you of how best to implement. You could load all the values into an array and increment an index counter, or your $db class may give you a more helpful accessor for getting the next value.
I'm creating a webpage that lists ten characters in a game based on their experience levels and displays them with a picture associated each character. My code works, but the output is in a column when I'd like it to be in a row. I did see where something very similar had been asked here: MySQL data from database align horizontally and I tried to follow that example but either ended up with errors or the faces didn't appear. I'm a hobbyist, I'm just doing this for friends, so my knowledge is pretty basic.
Relevant code:
<table border="3" width="90%">
<tr>
<th width="25%">XP</th>
<td>
<?php
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<left>";
echo "<table border='1'>";
echo "<tr><td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td></tr>";
echo "</table>";
echo "<br>";
}
?>
</td>
</tr>
</table>
Anyone got any suggestions? Thanks!
So after following Bombelman's suggestion below, I got it to work. In case anyone else runs into this problem, here is the working code:
<tr>
<th width="25%">Goody Two Shoes</th>
<td><?php
echo "<table border='1'><tr>";
echo "<left>";
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
?></td>
</tr>
place the "table" and "row" tag out of the loop, and have the results in between the "td" tags looped only.
Looking at your script, you have several tables.
Make sure only the < td > and < /td > tags are within the while-loop.
The output should be similar to my example.
Hope it helps !
<table style="width:100%">
<tr>
<td>Character 1</td>
<td>Character 2</td>
<td>Character 3</td>
<td>Character 4</td>
<td>Character 5</td>
</tr>
</table>
Looking at the sql queries makes me think you ought to be able to do a basic join upon the two tables rather than having nested queries within a loop. The generation of the html table should be fairly straightforward - iterate through the recordset results for rows in the table and iterate through the fields returned by the query for individual cells within the table row.
$sql='select l.*, d.face from `life` l
join `description` d on d.`charname`=l.`charname`
where l.`goodxp` > 0
order by l.`goodxp` desc
limit 10';
$res=$con->query( $sql );
/* fetch the column names into an array */
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
$html=array();
$html[]='<table>';
/* add field names as column headers */
$html[]='<tr>';
foreach( $fields as $field )$html[]='<th>'.$field.'</th>';
$html[]='</tr>';
/*
iterate through recordset,
add new row for every record
but table cell for every
field in record
*/
while( $rs=$res->fetch_object() ){
$html[]='<tr>';
foreach( $fields as $field ){/* show image or text */
$data = $field=='face' ? "<img src='pictures/{$rs->$field}' />" : $rs->$field;
$html[]='<td>'.$data.'</td>';
}
$html[]='</tr>';
}
$html[]='</table>';
/* render table */
echo implode( PHP_EOL, $html );
Depending upon the version of PHP you may get nagged at when using the array_walk function and passing the third argument by reference. If that is the case then change
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
for
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key ){
global $fields;
$fields[]=$item->name;
} );
I am fetching data in php from mysql table. Let say I retrieved 15 rows containing 15 unique ids. Now I want to get the the very first fetched id from the results.
This is what I'm trying..but its giving me the last id
<?php
$results = $db->query("SELECT * FROM orders where Sales_Rep='$sales_rep'");
while($row = $results->fetch_assoc()){
?>
<tr>
<td><?php echo $row["Order_ID"] ?></td>
<td><?php echo $row["Company_Name"]?></td>
</tr>
<?php
$last_order_date= $row["Order_ID"];
echo $last_order_date;
} //end of while loop
?>
you could simply add index like this
$i = 0;
while loop
$i++;
if($i === 1)
{get ID}
//rest of your while loop
endwhile;
you can modify your sql to
SELECT * FROM orders where Sales_Rep='$sales_rep' Order By Order_ID DESC
or you use this code
<?php
$results = $db->query("SELECT * FROM orders where Sales_Rep='$sales_rep'");
$i =0;
$first_id = 0;
while($row = $results->fetch_assoc()){
if ($i===0){
$first_id = $row["Order_ID"];}
$i++;
?>
<tr>
<td><?php echo $row["Order_ID"] ?></td>
<td><?php echo $row["Company_Name"]?></td>
</tr>
<?php
$last_order_date= $row["Order_ID"];
echo $last_order_date;
} //end of while loop
?>
your first Id is in $first_id
I want convert $RowNumber from string to a variable, for use in while, do is that possible?!how to do it?
$row1 = mysqli_query($Database,"SELECT * FROM Table1 ORDER BY ID");
$row2 = mysqli_query($Database,"SELECT * FROM Table2 ORDER BY ID");
// Others Rows code
for ($num = 1; $num <= 6; $num++)
{
$RowNumber = "row" . $num; // Save RowNumber for use in while
echo '<tr>';
// when it's used it not work becuse it's just a string only and
// i want convert it to variable to use in while
while($row = mysqli_fetch_array($RowNumber))
{
echo '<td>
<div class="Image_DIV" id="'; echo $row['DIV_ID']; echo '">
<table>
<tr><td class="Image"><img class="ImageOfDiv"
src="3DGallery/Chosen/Small/'; echo $row['src']; echo '"/></td></tr>
<tr>
<td class="ImageDescribe">'; echo $row['describe']; echo '</td></tr></table>
</div>
</td>';
}
echo '</tr><tr>';
}
Try ${$RowNumber} instead of $RowNumber for your purpose, If you need more info you can find it here. But as Mr. raina77ow has commented arrays are a good option.
If Table1 and Table2 have the same columns then you should UNION them together in your SQL then work on a single results set.
$results = mysqli_query($Database, "SELECT ID, DIV_ID, src, describe FROM `Table1` UNION SELECT ID, DIV_ID, src, describe FROM `Table2` ORDER BY ID");
echo '<tr>';
$x = 0;
while($row = mysqli_fetch_array($results))
{
echo '<td>';
echo $row['DIV_ID'];
echo $row['src'];
echo $row['describe'];
echo '</td>';
if( ++$x % 3 == 0 ) {
echo '</tr><tr>';
}
}
echo '</tr>';
Try this:
$rows[] = mysqli_query($Database,"SELECT * FROM Table1 ORDER BY ID");
$rows[] = mysqli_query($Database,"SELECT * FROM Table2 ORDER BY ID");
// Others Rows code
foreach ($rows as $current)
{
echo '<tr>';
// loop the query
while($row = mysqli_fetch_array($current))
{
echo '<td>
<div class="Image_DIV" id="'; echo $row['DIV_ID']; echo '">
<table>
<tr><td class="Image"><img class="ImageOfDiv"
src="3DGallery/Chosen/Small/'; echo $row['src']; echo '"/></td></tr>
<tr>
<td class="ImageDescribe">'; echo $row['describe']; echo '</td></tr></table>
</div>
</td>';
}
echo '</tr><tr>';
}
You cant assign variables like that without using php Eval: http://www.php.net/eval, but that is realy bad practise!
or using ${$var} syntax. But arrays is probably easier to work with.
How would I go about imposing a restriction on the number of HTML table columns when querying the database.
For example, I have a MySQL table with the following values:
myTable:
id color
1 red
2 blue
3 green
4 pink
5 purple
And when I run my query, instead of showing all rows in traditional table rows, e.g.
<table>
<?php
while {
echo "<tr><td>$row['color']</td></tr>;
}
?>
</table>
Instead, I would like to impose something where, every three td's, a new tr is created.
For example, it would output something like this:
<table>
<tr>
<td>red</td>
<td>blue</td>
<td>green</td>
</tr> <-- Notice how after 3 columns, a new table row is created.
<tr>
<td>pink</td>
<td>purple</td>
</tr>
</table>
Any way to achieve this?
In order to achieve this, you can use a combination of a counter and a modulus (%) operator:
<table>
<?php
$count = 0;
while($row = mysql_fetch_array($results)) {
$outputTr = ($count % 3) == 0;
if($outputTr) echo '<tr>';
echo '<td>' . $row['color'] . '</td>';
if($outputTr) echo '</tr>';
$count++;
}
?>
</table>
To achive this, put in a simple counter that resets every 3 table datas.
<?php
echo "<table><tr>";
$count = 0;
foreach($data as $key => $color)
{
if($count == 3)
{
$count = 0;
echo "</tr><tr>";
}
$count++;
echo "<td>".$color."</td>";
}
echo "</tr></table>";
?>