How to apply for loop to container in PHP - php

I am trying to run PHP code in WAMP server using MySQL. I am creating one container,
I don't know how many containers I need. Somehow I have the count of containers generated dynamically.
I want as many containers as count. I want to apply the for loop to the below code based on count of containers.
Also I need to create CSS container classes based on count.
In the query where i am using where clause(Where Entity='ATA'), i have array of data to apply in where clause, here i have shown only one(ATA), i need the containers based on count.
<form>
<div id="container">
<div id="content">
<!-- all you need with Tablecloth is a regular, well formed table. No need for id's, class names... -->
<table cellspacing="0" cellpadding="0">
<tr >
<th class="lightcolor" style="width:60px; height:30px;"><h2>Server Name</h2></th>
<th class="lightcolor" style="width:60px; height:30px;"><h2>IP Address</h2></th>
</tr>
<?php
$user_name = "root";
$password = "";
$database = "atssautomationgnoc";
$server = "localhost";
$con = mysqli_connect($server, $user_name, $password);
$db_found = mysqli_select_db($con,$database);
$query = "SELECT Servername,IPAddress FROM t_applicationstatus Where Entity='ATA' order by FIELD(LiveStatus,'RTO','OK')";
$result=mysqli_query($con,$query);
$Names = array();
if($result == FALSE)
{
die(mysql_error());
}
$i=0;
while ($row = mysqli_fetch_array($result))
{
$rowsA[] = $row;
}
foreach($rowsA as $row)
{
$rowsA[$i]=$row['Servername'];
$rowsA[$i] = $row['IPAddress'];
echo "<tr>";
echo "<td id=health>" ;
echo $row['Servername'] ;
echo " </td>";
echo "<td id=health>" ;
echo $row['IPAddress'];
echo " </td>";
echo " </td>";
echo "</tr>";
}
?>
</table>
</div>
</form>

Say, all of the criterias you wish to specify in where clause are stored in array $entityArr.You then should add an extra loop on top of the <table> element. Try the following code.
<div id="container">
<div id="content">
<?php
$user_name = "root";
$password = "";
$database = "atssautomationgnoc";
$server = "localhost";
$con = mysqli_connect($server, $user_name, $password);
$db_found = mysqli_select_db($con,$database);
$entityArr = array("ATA", "ANOTHER", "AND_ANOTHER");
$rowsA = array(); //define rowsA
foreach ($entityArr as $entity)
{
?>
<table cellspacing="0" cellpadding="0">
<tr>
<th class="lightcolor" style="width:60px; height:30px;"><h2>Server Name</h2></th>
<th class="lightcolor" style="width:60px; height:30px;"><h2>IP Address</h2></th>
</tr>
<?php
//use $entity below in where condition
$query = "SELECT Servername,IPAddress FROM t_applicationstatus Where Entity='".$entity."' order by FIELD(LiveStatus,'RTO','OK')";
$result=mysqli_query($con,$query);
$Names = array();
if($result == FALSE)
{
die(mysql_error());
}
//clear array
unset($rowsA);
while ($row = mysqli_fetch_array($result))
{
$rowsA[] = $row;
}
foreach($rowsA as $row)
{
$rowsA[$i]=$row['Servername']; //You'd better comment this line out
$rowsA[$i] = $row['IPAddress']; //And this one
echo "<tr>";
echo "<td>" ;
echo $row['Servername'] ;
echo " </td>";
echo "<td>" ;
echo $row['IPAddress'];
echo " </td>";
echo " </td>";//This is extra, simply remove this line
echo "</tr>";
}
?>
</table>
<?php
}
?>
</div> <!-- close #content -->
</div> <!-- close #container -->
There are various ways to do this, especially without executing sql statements in the loop. Hope that helps.

Related

How can I use a select box in HTML to search for a specific user in the database and show that information on a table?

I have a select box that shows the names of all the users in the database, however, I need, using a "Find Button" on the selected user on the combo box, that the data attached to that user shows up on the table
Table that currently shows the data of all users
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
$sql = "SELECT * FROM shifts";
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>
And here's the form that shows the users in the select box
<form name="form1" method="POST" action="">
<select name="getUser">
<?php
$res = mysqli_query($db, "SELECT * FROM shifts");
while ($row = mysqli_fetch_array($res))
{
?>
<option><?php echo $row ["name"]; ?></option>
<?php
}
?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
I'm trying to make it that so when the selected user in the combo box and the find button is pressed, that the data found goes all into the table described above.
I was maybe gonna try to attach a variable to the select box and compare it with the names field on the database.
Something like this
$query = "SELECT * FROM shifts WHERE $name == $nameSelected ";
Thanks.
first echo the user id into the option's value
<option value-"<?echo your id?>"><?php echo $row ["name"]; ?></option>
then when your form submits you get get the value from the $_POST
$userId = $_POST['getUser'];
not you can use the variable to query the database, but you should NEVER put it straight in, you should use PDO prepared statements to prevent injection.
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//something like this
$query = $conn->prepare("SELECT * FROM shifts WHERE id = :id");
$query->bindParam(':id',$userId,PDO::PARAM_INT);
$query->execute()
return $query->fetchAll();// I realised you wanted to get all the shifts so you don want fetchAll(),
notice that in mysql we only use a single = for our comparison unlike php. Also i've changed name to the unique row in the database, as unless your name field is unique how do you know which use called Dan you want?
If you want to do this without re-loading the whole page you will need to look into using Ajax and passing the value of the option tag via jQuery.
Here are some places to start:
https://www.w3schools.com/php/php_mysql_connect.asp
https://www.w3schools.com/xml/ajax_intro.asp
if you are not comfortable with javascript (AJAX), try on your form
<?php $res = mysqli_query($db, "SELECT * FROM shifts"); ?>
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"
<select name="getUser">
<option value='All'>All</options>
<?php
while ($row = mysqli_fetch_array($res)) { ?>
<option value='$row ["name"]'><?php echo $row ["name"]; ?></option>
<?php } ?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
And in your table
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
if ($_POST['getUser'] == 'All'){
$sql = "SELECT * FROM shifts";
} else {
$sql = "SELECT * FROM shifts WHERE name = " . $_POST['getUser'];
}
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>

How to create a table and style it in PHP

I have managed to take information from my database of the website, however I have no idea how to present the results in a table and how to style it. I tried putting <table> outside of the whole PHP, clearly did not work. I tried echoing a <table> tag before the result echo and a closing </table> tag after it, but that did not do it. This is the code I am working with:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<span style='color:white;'>"."<br> Name: ".$row["name"]."<br> Description: ".$row["description"]."<br> Content: ".$row["content"] ."<br>"."</p>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I am still new in PHP, trying to understand how the whole thing works. Thanks in advance!
<?php
function tableV1 ($row) {
echo '<tr>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['description'] . '</td>';
echo '<td>' . $row['content'] . '</td>';
echo '</tr>';
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
?>
Always do Database Connection first, before Outputting anything, that way, you can create custom error message to show instead of a failed database conntection or no content at all.
<style type="text/css">
table {}
tbody {}
td {}
th {}
thead {}
tr {}
</style>
Style is used inside the <head></head> to style the table, CSS it's called.
<table>
<thead>
<th>Name</th>
<th>Description</th>
<th>Content</th>
</thead>
<tbody>
<?php
// Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
tableV1($row);
}
} else {
echo '<tr><td colspan="3">0 results</td></tr>';
}
?>
</tbody>
</table>
Output contents from database.
<?php
$conn->close();
?>
Close database connection in the end. All together:
<?php
function tableV1 ($row) {
echo '<tr>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['description'] . '</td>';
echo '<td>' . $row['content'] . '</td>';
echo '</tr>';
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
table {}
tbody {}
td {}
th {}
thead {}
tr {}
</style>
</head>
<body>
<table>
<thead>
<th>Name</th>
<th>Description</th>
<th>Content</th>
</thead>
<tbody>
<?php
// Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
tableV1($row);
}
} else {
echo '<tr><td colspan="3">0 results</td></tr>';
}
?>
</tbody>
</table>
</body>
</html>
<?php
$conn->close();
?>
Try this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo "<table>";
echo "<thead>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
</thead>";
echo "<tbody>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["description"]."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<table>';
echo '<tr><td>Name</td><td>Description</td><td>Content</td></tr>'
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["name"]."</td><td>".$row["description"]."</td><td>".$row["content"] ."</td></tr>";
}
echo '</table>';
} else {
echo "0 results";
}
$conn->close();
?>
The basic table format is this
for example:
<table>
<tr>
<td>row 1 item 1</td>
<td>row 1 item 2</td>
</tr>
<tr>
<td>row 2 item 1</td>
<td>row 2 item 2</td>
</tr>
</table>
so try:
if ($result->num_rows > 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["description"]."</td>";
echo "<td>".$row["content"]."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Try this approach:
[... some HTML header and code ...]
<table>
<thead>
<tr><th>Name</th><th>Description</th><th>Content</th></tr>
</thead>
<tbody>
<?php
[ ... extract something from the database ...]
while($row = $result->fetch_assoc())
{
echo "<tr><td>$row[name]</td><td>$row[description]</td><td>Content</td></tr>\n";
}
}
?>
</tbody>
</table>
[... some HTML footer ...]
Obviously, replace the [...] sections with your own code. The idea is here to use PHP to output the dynamic part of your HTML code, and is the power of PHP combined with HTML.
I try to avoid "echoing" to much HTML in my PHP, but it does work (reference other answers).
Detail: when setting up a <table> you should setup a header section <thead> <tfoot> (if applicable) and body section <tbody>. Ref What is the purpose for HTML's tbody?

Export MSSQL Query To CSV File From PHP

I am using the below syntax within my joomla article and I am in need of a way to add a php button (I know the syntax or this) - and on the button press event fire off exporting the SQL Query Results (header and data) to a csv file. This is the syntax i am using to populate a table. Is this easily ammendable to add in a function to export to .csv also?
<html>
<body>
<form method="POST">
</form>
</body>
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'IP Address';
$option['user'] = 'username';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance($option);
$query = $db->getQuery(true);
$query = "Select height, weight, userID, name from personelinfo;";
$db->setQuery($query);
$query = $db->loadObjectList();
if ($query)
{
?>
<table border="1">
<thead>
<tr>
<th>height </th>
<th>weight </th>
<th>userID </th>
<th>name </th>
</tr>
</thead>
<?php
foreach ($query as $res)
{
print "<tr>";
print "<td>" . $res->height . "</td>";
print "<td>" . $res->weight . "</td>";
print "<td>" . $res->userID . "</td>";
print "<td>" . $res->name . "</td>";
print "</tr>";
}
}
?>
</table>
</html>
You want to have much more separation between your PHP and HTML output. This will serve you well when you want to output other formats such as CSV. Here I get the database results at the top of the file and load them into an array, before any output is done — ideally this would be done in a separate file.
Then we can check if CSV output is desired. I've changed the database code to return an associative array instead of an object, this makes it trivial to pass each row to fputcsv().
Note I've also used alternative syntax and short echo tags to reduce PHP/HTML intermixing. This is a good practice to get into. Finally, your HTML was a mess; you were closing the body before outputting the table, and omitting the <head> and <tbody> elements.
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'IP Address';
$option['user'] = 'username';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance($option);
$query = "Select height, weight, userID, name from personelinfo;";
$db->setQuery($query);
$resultset = $db->loadAssocList();
if (!empty($_GET["csv"])) {
$out = fopen("php://stdout");
header("Content-Type: text/csv");
foreach ($resultset as $res) {
fputcsv($out, $res);
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<?php if(count($resultset):?>
<table border="1">
<thead>
<tr>
<th>height </th>
<th>weight </th>
<th>userID </th>
<th>name </th>
</tr>
</thead>
<tbody>
<?php foreach($resultset as $res):?>
<tr>
<td><?= $res["height"] ?></td>
<td><?= $res["weight"] ?></td>
<td><?= $res["userID"] ?></td>
<td><?= $res["name"] ?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<form method="get">
<button type="submit" name="csv" value="1">Export to CSV</button>
</form>
<?php endif;?>
</body>
</html>

Search tables from SQL and show their data on page

I've been trying to find an easy way for this. A search (dropdown menu) of all tables in mysql, and show their content when I click the table I want to show on the page. Instead of showing just every table on the page I thought it can be easier? Any help would be appreciated! My code so far:
<?php
$host = "localhost";
$user = "heijsdb_user";
$pass = "maus";
$db_name = "heijsdb";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
echo "borsten HFP controle";
$result = mysqli_query($connection,"SELECT * FROM borstenHFPcontrole");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table w3-table-all" border="2px">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
////////////////////////////////////////////////////////////////////////////////////////////////////////////
This is pretty much the idea, you can play from here and adapt it to your solution. Sorry I used my way, I prefer PHP template style when embedding in HTML. ;)
$host = "localhost";
$user = "heijsdb_user";
$pass = "maus";
$db_name = "heijsdb";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//check if the form was submitted
$table = filter_input(INPUT_POST, 'table', FILTER_SANITIZE_STRING);
?>
<html>
<head>
<title>showing table content on user action</title>
</head>
<body>
<div>
<form id="form-menu" method="post">
<label for="select-menu">Choose a table</label>
<select id="select-menu" name="table">
<option></option>
<?php
$result = mysqli_query($connection,"SELECT table_name FROM information_schema.tables where table_schema='test'"); // <-- the table_schema field here is your database name, change 'test' for yours
while ($row = mysqli_fetch_array($result)) : $selected = $row['table_name'] == $table ? 'selected' : ''; ?>
<option value="<?php echo $row['table_name'] ; ?>" <?php echo $selected; ?>><?php echo $row['table_name'] ; ?></option>
<?php endwhile; ?>
</select>
</form>
<hr>
<div>
<?php if (empty($table)) : ?>
<h3>Please select a table to show its content</h3>
<?php else : ?>
<h3>Content for the table `<?php echo $table; ?>`</h3>
<?php
$result = mysqli_query($connection,"SELECT * FROM `{$table}`");
$all_property = []; //declare an array for saving property
?>
<!-- showing property -->
<table class="data-table w3-table-all" border="2px">
<tr class="data-heading"> <!-- initialize table tag -->
<?php while ($property = mysqli_fetch_field($result)) : ?>
<td><?php echo $property->name; ?></td> <!-- get field name for header -->
<?php $all_property[] = $property->name; //save those to array ?>
<?php endwhile; ?>
</tr> <!-- end tr tag -->
<!-- showing all data -->
<?php while ($row = mysqli_fetch_array($result)) : ?>
<tr>
<?php foreach ($all_property as $item) : ?>
<td><?php echo $row[$item]; ?></td> <!-- get items using property value -->
<?php endforeach; ?>
</tr>
<?php endwhile; ?>
</table>
<?php endif; ?>
</div>
</div>
<script>
document.getElementById('select-menu').addEventListener('change', function() {
document.getElementById('form-menu').submit();
});
</script>
</body>
</html>
Handy links:
- Get table names using SELECT statement in MySQL
- Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.
Hope this helps :)

Get all data for parent and child rows

I want to retrieve all mysql table data using this script:
<?php
//WHERE id_post = '$id_post'
$sq = mysql_query("SELECT * FROM article_comments ") or die(mysql_error());;
connect();
while($row = mysql_fetch_assoc($sq)){
$result[$row["parent_id"]][] = $row["id"];
}
$rowIsOpened = false; //Indicates whether a row is currently opened.
//I'm using $rowIsOpened because the row immediately after the rowspanned cell shouldn't be closed.
echo <<<HTML
<table style="border-color: black;border-style: solid;">
<thead>
<tr>
<th>Parent</th>
<th>Children</th>
</tr>
</thead>
<tbody>
HTML;
//Echo a bunch of HTML before actually looping
foreach ($result as $parent => $children) {
echo "<tr style='border-color: black;border-style: solid;vertical-align:top;'>";
echo "<td rowspan=";
echo count($children); //Span over <how many children are> rows
echo " style='border-color: black;border-style: solid;' >$parent</td>";
$rowIsOpened = true; //Row is opened
foreach ($children as $child) {
if (!$rowIsOpened) {
echo "<tr>";
} //Only open a row if row is not opened
echo "<td style='border-color: black;border-style: solid;'>$child</td>";
echo "</tr>";
$rowIsOpened = false; //Row is now closed. Ready for next iteration.
}
}
//Close the table tags etc.
echo <<<HTML
</tbody>
</table>
HTML;
?>
This script creates an output table like that
Parent Children
0 1
3
4
5
1 1
2
My problem is when i try to add the other data from the mysql table: comment, name, date etc.
I have to replace these numbers with:
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo $name; ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
I tried this but it does not work and i didn't got much about arrays....
A little explaining would help me understand the concept better :)
$id_post = "1";
$name = array();
$email = array();
$comment = array();
$date = array();
//WHERE id_post = '$id_post'
$sq = mysql_query("SELECT * FROM article_comments WHERE id_post = '$id_post' ") or die(mysql_error());;
connect();
while($row = mysql_fetch_assoc($sq)){
$result[$row["parent_id"]][] = $row["id"];
$comment[$row['id']] = $row['comment'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
// $grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
}
$rowIsOpened = false; //Indicates whether a row is currently opened.
//I'm using $rowIsOpened because the row immediately after the rowspanned cell shouldn't be closed.
echo <<<HTML
<table style="border-color: black;border-style: solid;">
<thead>
<tr>
<th>Parent</th>
<th>Children</th>
</tr>
</thead>
<tbody>
HTML;
//Echo a bunch of HTML before actually looping
foreach ($result as $parent => $children) {
echo "<tr style='border-color: black;border-style: solid;vertical-align: top;'>";
echo "<td rowspan=";
echo count($children); //Span over <how many children are> rows
echo " style='border-color: black;border-style: solid;width:400px;' >$parent
<div class='cmt-cnt'>
<img src='".$grav_url."' />
<div class='thecom'>
<h5>".$name."</h5><span data-utime='1371248446' class='com-dt'>".$date."</span>
<br/>
<p>
".$comment."
</p>
</div>
</div>
</td>";
$rowIsOpened = true; //Row is opened
foreach ($children as $child) {
if (!$rowIsOpened) {
echo "<tr>";
} //Only open a row if row is not opened
echo "<td style='border-color: black;border-style: solid;width:400px;'>$child</td>";
echo "</tr>";
$rowIsOpened = false; //Row is now closed. Ready for next iteration.
}
}
//Close the table tags etc.
echo <<<HTML
</tbody>
</table>
HTML;
?>
You can add the entire result array to your parent array like this:
// I like to declare my variables and arrays
$results = array();
while ($row = mysql_fetch_assoc($sq)){
// I don't like to assume that I can append to array indexes that don't exist
if (!array_key_exists($row['parent_id'], $results)){
$results[$row['parent_id']] = array();
}
$results[$row['parent_id']][] = $row;
}
Then when you output, you can do this:
foreach ($results as $parent_id => $children){
// I'm leaving out the table because this is just for an example
echo $parent_id . '<br>';
foreach ($children as $child){
echo ' - ' . $child['commment'] . '<br>';
echo ' - ' . $child['date'] . '<br>';
}
}

Categories