I am trying to create a table from a sql query but I need to only have 3 results per table row.
I have a list of about 47 names so I have no problem printing them on a new line but how would I go about creating a table where the while loop would print a table row then print 3 table data cells with the query then create a new row for the next 3 values?
Exa:
result_1 | result_2 | result_3
result_4 | result_5 | result_6
result_7 | result_8 | result_9
Current While Loop:
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td><input type='checkbox'> ".$row['name']."</td>";
echo "<td><input type='checkbox'> ".$row['name']."</td>";
echo "<td><input type='checkbox'> ".$row['name']."</td>";
echo "</tr>";
}
Database Structure:
id | name
1 | result_1
2 | result_2
3 | result_3
4 | result_4
Thanks in advance!
You can use the modulus operator (%) to check if you're ready for a new line.
$number_of_names = count($names);
$number_of_columns = 3; //you can change this at any point
echo "<table><tr>";
for($i=0;$ i<$number_of_names; $i++){
echo "<td>" . $names[$i] . "</td>";
if ($i % $number_of_columns == ($number_of_columns - 1) && $i<$number_of_names-1){
echo "</tr><tr>";
}
}
echo "</tr></table>";
Try looping through the results using a for loop, then compare the remainder of dividing the iterator by 3, using the modulus operator.
echo "<tr>";
for($i = 0; $i<mysql_num_rows($result); $i++) {
if($i%3==0) {
echo "</tr><tr>";
}
$row = mysql_fetch_assoc($result)
echo "<td><input type='checkbox'> ".$row['name']."</td>";
}
echo "</tr>";
Related
I have an sql query that looks like this:
//do a query to find all the samples in the currently selected rack
$sql = "SELECT SampleID, ColumnNumber, RowNumber FROM Samples WHERE Rack = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $rack);
$stmt->execute();
$rackContents = $stmt->get_result();
In each rack, a ColumnNumber and RowNumber combination describes a position in the rack, starting with:
ColumnNumber = 1, RowNumber = 1 then
ColumnNumber = 2, RowNumber = 1
and so on until (for example, in a 10x10 rack)
ColumnNumber = 10, RowNumber = 10.
I want to display the SampleIDs in each position of the rack in a table. Using a nested loop, I can draw a table that has a <td> for each rack position. What I can't figure out is how to display the SampleID based on the ColumnNumber and RowNumber combination for each position.
This is how I build the table:
//start a loop that visits each row
$rownumber = 1;
while ($rownumber <= $numberofrows){
//start a loop that visits each column
//start a row
echo "<tr>";
$columnnumber = 0;
while ($columnnumber <= $numberofcolumns){
if ($columnnumber == 0){
echo "<td>" . $rownumber . "</td>";
}
else{
//find the sample number for the relevant column and row
//inside the array we got in an sql query earlier, $rackContents
echo "<td>" . x . "</td>";
//What do I put in place of the x to output the appropriate
//SampleId for the ColumnNumber/RowNumber combo?
}
$columnnumber++;
}//end the columnnumber loop
//end the row
echo "</tr>";
$rownumber++;
}//end the rownumber loop
I've been looking at array_search, but I just can't get anywhere.
If I am understanding you correctly I think you just need to fetch the array from your result. Although I am not sure this is the result you actually want.
while ($rackContent = $rackContents->fetch_array(MYSQLI_NUM))
$rownumber = 1;
while ($rownumber <= $numberofrows){
echo "<tr>";
$columnnumber = 0;
while ($columnnumber <= 3){
if ($columnnumber == 0){
echo "<td>" . $rownumber . "</td>";
} else {
echo "<td>" . $rackContent['SampleID'] . "</td>";
}
$columnnumber++;
echo "</tr>";
$rownumber++;
}
}
But I think you probably want something more like this.
while ($rackContent = $rackContents->fetch_array(MYSQLI_NUM))
echo "<tr>";
echo "<td>" . $rownumber . "</td>";
echo "<td>" . $rackContent['SampleID'] . "</td>";
echo "<td>" . $rackContent['ColumnNumber'] . "</td>";
echo "<td>" . $rackContent['RowNumber'] . "</td>";
echo "</tr>";
}
Suppose there is a number of item in array.which may be odd or even like I have an array which contain item from a to z Now I want to display that item in table . But As you know That There are 23 alphabets I want to display these alphabets in table which contains only 5 column in the last you got only three alphabets I want to display them in table . In the last I want that there should be three column not 5.
Here is my code i could not get that what should i do?
But the problem I faced in the below code is that the second loop is not correct.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$count= sizeof($arr);
$row=ceil($count/5);
echo "<table border='1'>";
for($r=0;$r<$row;$r++){
echo "<tr>";
for($j=0;$j<=5;$j++){
echo "<td>'".$arr[$j]."'</td>";
}
echo "</tr>";
}
echo "</table>";
?>
My approach uses array_slice to take out pieces of the source and build rows:
$arr=array('a','b','c','d','e','f','g','h');
$offset = 0;
$num_columns = 5; //adjust number of columns
$table_html = "<table border='1'>";
while($slice = array_slice($arr,$offset,$num_columns)){
$offset += $num_columns;
$row_html = '';
foreach($slice as $n) $row_html .= "<td>$n</td>";
$table_html .= "<tr>$row_html</tr>";
}
$table_html .= '</table>';
echo $table_html;
Live demo
Try below code. Declaring number of column required in a variable, so which can be changed any time. closing the tr tag when loop count is same as number of columns to be displayed.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$columnLength = 5;
echo "<table border='1'>";
echo "<tr>";
for($r=0;$r<count($arr) ; $r++){
echo "<td>'".$arr[$r]."'</td>";
if($r + 1 == $columnLength ) {
echo "</tr>";
}
}
echo "</table>";
?>
while($row = mysql_fetch_array($result41))
{
echo "<tr><td align='center'>" .$row['AdmitRollNo'] . " </td></tr>";
}
This returns around 50 Admit Roll Numbers in a single column of the table. But I need the output in 5 columns containing respectively 9, 10, 7, 11, 13 items.
How to proceed?
Using a modulus operator in PHP would be a good start. This should work:
// Set how many items per column.
$per_column = 9;
// Set the opening table row.
echo "<tr>";
// Setting the counter to 0.
$counter = 0;
while ($row = mysql_fetch_array($result41)) {
// Increment the counter by one.
$counter++;
// Do a modulus check between the counter & the per column value.
if ($counter % $per_column == 0) {
echo "</tr><tr>";
}
// Echo the table data columns.
echo "<td align='center'>" . $row['AdmitRollNo'] . " </td>";
}
// Set the closing table row.
echo "</tr>";
But you say 9, 10, 7, 11, 13 items per each column. A bit trickier. But I believe that can be done. And here is a concept I just whipped up. The idea is there is an array of per column values named $per_column_array plus a counter named $per_counter. The first time the modulus is reached, the counter is incremented by one, so the next $per_column_array value is grabbed.
// Set how many items per column.
$per_counter = 0;
$per_column_array = array(9, 10, 7, 11, 13);
// Set the opening table row.
echo "<tr>";
// Setting the counter to 0.
$counter = 0;
while ($row = mysql_fetch_array($result41)) {
// Increment the counter by one.
$counter++;
// Do a modulus check between the counter & the per column value.
if ($counter % $per_column_array[$per_counter] == 0) {
$per_counter++;
echo "</tr><tr>";
}
// Echo the table data columns.
echo "<td align='center'>" . $row['AdmitRollNo'] . " </td>";
}
// Set the closing table row.
echo "</tr>";
ANOTHER EDIT: Here is an attempt with columns. Please feel free to adjust but the basic concept is the values are placed in a nested <table> within the <table> structure you already have:
// Set how many items per column.
$per_counter = 0;
$per_column_array = array(9, 10, 7, 11, 13);
// Set the opening table row.
echo "<tr><td>";
echo "<table>";
while ($row = mysql_fetch_array($result41)) {
// Increment the counter by one.
$counter++;
// Do a modulus check between the counter & the per column value.
if ($counter % $per_column_array[$per_counter] == 0) {
$per_counter++;
echo "</table>";
echo "</td>";
echo "<td>";
echo "<table>";
}
// Echo the table data columns.
echo "<tr><td align='center'>" . $row['AdmitRollNo'] . " </td></tr>";
}
// Set the closing table row.
echo "</table>";
echo "</td></tr>";
I'm creating a table using a PHP from the MySQL query which return a total count of rows from two columns in the database, "total_tr" and "total_rc".
I've already done and successfully view the count in the PHP table, the coding is:
while($row = mysql_fetch_array($result))
{
echo "<tbody>";
echo "<tr>";
echo "<td>Zone</td>";
echo "<td>" . $row['segment_code'] . "</td>";
echo "<td>" . $row['COUNT(total_tr)'] . "</td>";
echo "<td>" . $row['COUNT(repeat_rc)'] . "</td>";
echo "</tr>";
echo "</tbody>";
}
My problem now is, I want to take the total count value of "total_tr", divided with total count of "repeat_rc" and multiply with 100 to get the percentage of total_rc.
Any ideas on how can I do that?
$myresult = $row['COUNT(total_tr)'] / $row['COUNT(repeat_rc)'] * 100;
Keep a running count as you echo the rows
$total_tr = 0;
$total_rc = 0;
while($row = ...) {
$total_tr += $row['COUNT(total_tr)']);
$total_rc += $row['COUNT(repeat_rc)']);
... html here ...
}
echo $total_tr / $total_rc * 100;
<?php
$say = array("ann","brenda","charles","david",
"edward","florence","geoff","harry",
"ingrid","james","kelly","liam");
$columns = 5;
for ($p=0; $p<count($say); $p++) {
// Start of table or line?
if ($p==0) { // Start of table
print "<table border=0><tr>";
} elseif ($p%$columns == 0) { // Start of row
print "<tr>";
}
print "<td>".htmlspecialchars($say[$p])."</td>";
// End of table or line?
if (($p+1)%$columns == 0) { // End of row
print "</tr>";
}
if ($p==count($say)-1) { // End of table
$empty = $columns - (count($say)%$columns) ;
if ($empty != $columns) {
print "<td colspan=$empty> </td>";
}
print "</tr></table>";
}
}
?>
The result:
ann brenda charles david edward
florence geoff harry ingrid james
kelly liam
I'm trying to do the same with mysql
so far i got
<?php
$con = mysql_connect("localhost","root","lol");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM test");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$nam=$row['nam'];
$columns = 3;
for ($p=0; $p<count($id); $p++) {
// Start of table or line?
if ($p==0) { // Start of table
print "<table border=0><tr>";
} elseif ($p%$columns == 0) { // Start of row
print "<tr>";
}
print "<td>".$nam."</td>";
// End of table or line?
if (($p+1)%$columns == 0) { // End of row
print "</tr>";
}
if ($p==count($nam)-1) { // End of table
$empty = $columns - (count($nam)%$columns) ;
if ($empty != $columns) {
print "<td colspan=$empty> </td>";
}
print "</tr></table>";
}
}
}
mysql_close($con);
?>
Result:
ann
brenda
charles
david
edward
florence
geoff
harry
ingrid
james
kelly
liam
Question: what's wrong?
Dabase table
id nam
1 ann
2 brenda
3 charles
4 david
5 edward
6 florence
7 geoff
8 harry
9 ingrid
10 james
11 kelly
12 liam
I'd suggest that you split your code into two distinct functions.
One function will read information from the database or the array, the other will format the output.
Right now, it looks an awful lot like you took your first chunk of code and put it into the middle of the while loop in the second piece.
MySQL is returning results to you, one result row at a time. So what you should do is collect all those results first and then print them out second (either that, or make a counter on the number of rows returned). In your second piece of code, you're treating each result row as you were the entire array of results in the first piece.
That is, the line while($row = mysql_fetch_array($result)) returns a single row from the table.
Because of this, the line $id=$row['id']; does not assign an array to $id.
Because of this, the line for ($p=0; $p<count($id); $p++) { iterates over a single item, resulting in what you're seeing.
My code still looks a little hackish, but it may give you an idea. I'm afraid I haven't tested it.
print "<table><tr>";
$p=0;
$columns=3;
while( $row = mysql_fetch_array($result) ) {
if ( $p>0 && ($p % $columns)==0 )
print "</tr><tr>";
print "<td>{$row['nam']}</td>";
$p++;
}
for(true;($p % $columns)!=0;$p++) //Finish off $p from above
print "<td> </td>";
print "</tr></table>";
To do this in a more modular way:
function display($stuff,$cols){
//Make sure the table is some multiple of $cols to eliminate special cases
//Hackish
while( (count($stuff) % $cols)!=0 )
$stuff.push_back(" ");
//Start table and first row, eliminating another special case
print "<table><tr>";
for($i=0;$i<count($stuff);$i++){
if($i>0 && ($i % $cols)==0)
print "</tr><tr>";
print "<td>{$stuff[$i]}</td>";
}
print "</tr></table>";
}
$names=array()
while( $row=mysql_fetch_array($result) )
$names.push_back($row['nam']);
display($names,5);