In an php/html document could I create a loop to create html table rows as long as there is a rows to be read from a MySQL database table?
I could then populate the html table with the data but I first need to know if I can make a loop that will only run as longs as there are
more database rows to be read. Thanks.
diafol
Yes - use concatenation. Example:
$output = "";
while($data = $stmt->fetch())
{
$output .= "<tr><td>{$data['field1']}</td><td>{$data['otherfield']}</td></tr>";
}
Then:
<table>
<thead>
<tr>
<th>Field 1 Heading</th>
<th>OtherField Heading</th>
</tr>
</thead>
<tbody>
<?=$output?>
</tbody>
</table>
jkon 636 Posting Whiz in Training Featured Poster
Diafol answer is (of course) accurate and enough. I hope he don't mind I wrote one more example using a very simple view component HTML generator class for tables.
<?php
$database = "test";
$username = "testuser";
$password = "testpassword";
$db = new PDO("mysql:host=localhost;dbname=".$database , $username, $password);
$statement = $db->prepare("SELECT * FROM persons WHERE age > ?");
$statement->execute( array(18) );
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
$personsTable = "";
if(count($rows) > 0)
{
$table = new View_Generator_Table( array("First Name","Last Name","Age") );
foreach($rows as $row)
{
$table->addCell( $row["firstName"] );
$table->addCell( $row["lastName"] );
$table->addCell( $row["age"] );
}
$personsTable = $table->generate();
}
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>An example with a table</title>
</head>
<body>
HERE ARE PERSONS OLDER THAN 18
<br />
<?=$personsTable?>
</body>
</html>
<?php
/**
* A very simple view component generator for tables
*/
class View_Generator_Table
{
private $headers = array();
private $cells = array();
/**
* Array of the table headers
* @param array of strings $headers
*/
public function __construct($headers)
{
$this->headers = $headers;
}
/**
* Adds a cell to the table
* @param string $cell
*/
public function addCell($cell = "")
{
$this->cells[] = $cell;
}
/**
* Generates and returns the table html in a string
* @return string
*/
public function generate()
{
$re = "";
$columns = count($this->headers);
if($columns > 0)
{
$re .= "<table><thead><tr>";
// Adding the headers
foreach($this->headers as $header)
{
$re .= "<th>".$header."</th>";
}
$re .= "</thead></tr>";
$totalCells = count($this->cells);
if($totalCells > 0)
{
// Adding the data cells
$re .= "<tbody>";
for($i=0; $i < $totalCells; $i++)
{
$currentColumn = $i % $columns;
if($currentColumn == 0)
{
$re .= "<tr>";
}
$re .= "<td>".$this->cells[$i]."</td>";
if($currentColumn == $columns - 1)
{
$re .= "</tr>";
}
}
// If there the number of the cells don't much the number of the
// columns then we add some empty cells
if($currentColumn !== $columns - 1)
{
for($i = $currentColumn ; $i < $columns - 1; $i++)
{
$re .= "<td></td>";
}
$re .= "</tr>";
}
$re .= "</tbody>";
}
$re .= "</table>";
}
return $re;
}
}
?>
diafol commented: Hey, I like it! :) +15
diafol
Seeing as you're using a fetchAll()
so the complete result is in array format, you could have a simple additional method for bare bones data (not requiring any special preparation):
echo $table->addTable($headerArray, $fieldNameArray, $data);
jkon 636 Posting Whiz in Training Featured Poster
Yes of course diafol , we could also have a View Util class for data tables e.g.
<?php
class View_Utils_Table
{
/**
* Creates a new View_Generator_Table using the headers and add cells
* defined by the fields using data from rows
* @param array of strings $headers
* @param array of strings $fields
* @param array of strings $rows
* @return string
*/
public static function generateDataTable($headers,$fields,$rows)
{
$table = new View_Generator_Table( $headers);
if(count($rows) > 0)
{
foreach($rows as $row)
{
foreach($fields as $field)
{
$table->addCell( $row[$field] );
}
}
}
return $table->generate();
}
}
?>
and then we would just have
$personsTable = View_Utils_Table::generateDataTable(
array("First Name","Last Name","Age")
,array("firstName","lastName","age")
, $rows);
(indent here is not the best since I am used in 80 chars lines and this WYSIWYG has other opinions :) )
diafol commented: Nice ;) +0
lewashby 56 Junior Poster
Thanks all.
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.