Get all data for parent and child rows - php

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>';
}
}

Related

PHP dynamic table header and dynamic table rows based on header - tried everything

I am trying to build a editable table with dynamic headers and dynamic rows based on header, but I lost my way in the process.
I got the dynamic headers:
<div class="jumbotron">
<div class="container">
<table class='table'>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Emails</th>
<?php
include("../connection/connection.php");
$get_title = "SELECT DISTINCT(title) FROM attendance";
$query1 = mysqli_query($con,$get_title);
if ($query1) {
# code...
while ($row=mysqli_fetch_array($query1)) {
# code...
$title[] = $row['title'];
}
$count = count($title);
for ($i=0; $i <$count ; $i++) {
# code...
echo "<th>".$title[$i]."</th>";
}
}
?>
</tr>
</thead>
<tbody>
<?php
$get_emails = "SELECT * FROM subjects";
$query2 = mysqli_query($con,$get_emails);
if ($query2) {
# code...
while ($row=mysqli_fetch_array($query2)) {
# code...
$emails = $row['email'];
$id = $row['id'];
$get_name = "SELECT * FROM users";
$query3 = mysqli_query($con,$get_name);
if ($query3) {
# code...
while ($row=mysqli_fetch_array($query3)) {
# code...
$fullname = $row['user_fullname'];
echo "<tr>";
echo "<td contenteditable>".$id."</td>";
echo "<td contenteditable>".$fullname."</td>";
echo "<td contenteditable>".$emails."</td>";
echo "</tr>";
}
} else {
echo "<tr>";
echo "<td contenteditable>".$id."</td>";
echo "<td contenteditable></td>";
echo "<td contenteditable>".$emails."</td>";
echo "</tr>";
}
}
} else {
echo "<tr>";
echo "<td contenteditable></td>";
echo "<td contenteditable></td>";
echo "<td contenteditable></td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
Now I need to echo the table td which would be dynamic based on the headers after the emails - td inside the tr.
Any help is appreciated.
The major problem you have is that the array element isn't going to be called title but rather DISTINCT(title) because you didn't alias it as something else, the code below shows it being aliased back as title, and as well eliminating what appears to be an unnecessary loop.
$get_title = "SELECT DISTINCT(title) title FROM attendance";
$query1 = mysqli_query($con,$get_title);
if ($query1) {
# code...
while ($row=mysqli_fetch_array($query1)) {
# code...
echo "<th>".$title[$i]$row['title']."</th>";
}
}

getting value of array check box and textbox in table

i'm a beginner in php and i'm hoping that somebody here can help me in this.
i have a table that has a check box to select an item and a text box to indicate the quantity the person wants to borrow. i was wondering how i can retrieve both these data and then save them in my database.
here is a part of my code:
<td width="30">
<input id="optionsCheckbox" class="uniform_on" name="selector[]" type="checkbox" value="<?php echo $id; ?>">
</td>
<td><?php echo $row['item_code']; ?></td>
<td><?php echo $row['item_name']; ?></td>
<td align="center">
<img class="img-rounded" src="<?php echo $row['item_image'];?>" border="0" onMouseOver="showtrail('<?php echo $row['item_image'];?>','<?php echo $row['item_code'].": ".$row['item_name'];?> ',200,5)" onMouseOut="hidetrail()"></a></td>
<td><?php echo $row['item_quantity'] - $row['item_consumption']; ?> <?php echo $row['unit']; ?></td>
<td><input type="text" name="consume[]" pattern="[0-9]{1,4}"/></td>
here's what i have so far:
$id=$_POST['selector'];
$consume= $_POST['consume'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
$query = $conn->query("select * from item where item_id ='$id[$i]'")or die(mysql_error());
$row = $query->fetch();
$code = $row['item_code'];
$name = $row['item_name'];
echo $code; echo $name;
echo $id;
}
$x = count($consume);
for($y=0; $y < $x; $y++)
{echo $consume;
}
the echos are just for checking if the data goes through. i'm just making sure they do before i make a query for table insertion.
what i'm trying to do is to post them on another page, display them in a table (a la shopping cart) and then make the borrower fill out a form with his details.
ok, using gul's answer below, this is what i did:
$id = $_POST['selector'];
$consume = $_POST['consume'];
//array var for getting the values
$ids = ''; $consumes='';
//loop the posted array
for($i=0;$i<count($id);$i++)
{
$ids .= $id[$i].',';
$consumes.="'".$consume[$i]."',";
}
//remove the last comma
$ids = substr($ids,0,-1);
$consumes = substr($consumes,0,-1);
$query = $conn->query("select * from item where item_id IN($ids)")or die(mysql_error());
//table element
echo "<table border='1' style='border-collapse:
collapse;border-color: silver;'>";
echo "<tr style='font-weight: bold;'>";
echo "<td width='150' align='center'>Item Code</td>";
echo "<td width='150' align='center'>Item Name</td>";
echo "<td width='150' align='center'>Quantity</td>";
echo "</tr>";
//get data in table
$row = $query->fetch();
$code = $row['item_code'];
$name = $row['item_name'];
$table ="";
$table.="<tr>";
$table.="<td>".$code."</td>";
$table.="<td>".$name."</td>";
$table.="<td>".$consumes."</td>";
$table.="</tr>";
$table.="</table>";
//echo the table
echo $table;
however, when i select multiple items, only the last one shows up, but the consumes show up like this:
consume shows in one cell with single quotes and comma. help?
Try like this:
//first get the post
$id = $_POST['selector'];
$consume = $_POST['consume'];
//array var for getting the values
$ids = ''; $consumes='';
//loop the posted array
for($i=0;$i<count($id);$i++)
{
$ids .= $id[$i].',';
//$consumes.="'".$consume[$i]."',";
}
//remove the last comma
$ids = substr($ids,0,-1);
$query = $conn->query("select * from item where item_id IN($ids))or die(mysql_error());
//table element
$table = "<table border='1'>";
$table.="<tr>";
$table.="<th>Code</th><th>Name</th>";
$table.="</tr>";
//get data in table
$row = $query->fetch();
$code = $row['item_code'];
$name = $row['item_name'];
$table.="<tr>";
$table.="<td>".$code."</td>";
$table.="<td>".$name."</td>";
$table.="</tr>";
$table.="</table>";
//echo the table
echo $table;
ok, so i tried this and it worked. thanks to gul for helping me.
$id = $_POST['selector'];
$consume = $_POST['consume'];
//array var for getting the values
$data = array();
//loop the posted array
for($i=0;$i<count($id);$i++)
{
$row = array('selector'=>$id[$i],'consume'=>$consume[$i]);
//push in array
array_push($data,$row);
$query = $conn->query("select * from item where item_id ='$id[$i]'")or die(mysql_error());
$row = $query->fetch();
$code = $row['item_code'];
$name = $row['item_name'];
while ($row = $query->fetch()) {
$id = $row['id'];
}
?>
<tr>
<td><?php echo $code; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $consume[$i]; ?></td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table>

Can't make it appear in the correct way PHP

we have an assignment for today in which we have to echo some data of the database. The data is month, case, vehicle_id. In a month there can be many cases and in a case there can be many vehicle_ids. What i have achieve to do is to show it in the following way
month st_case veh_id
1 10001 1000011
1 10002 1000021
1 10002 1000022
2 10058 1000581
using this code:
<table border="1">
<tr>
<th>month</th>
<th>st_case</th>
<th>veh_id</th>
</tr>
<?php
// Loop on rows in the result set.
for($ri = 0; $ri < $numrows; $ri++) {
echo "<tr>\n";
$row = pg_fetch_array($result, $ri);
echo " <td>", $row["month"], "</td>
<td>", $row["st_case"], "</td>
<td>", $row["veh_id"], "</td>
</tr>
";
}
pg_close($link);
?>
</table>
The problem is that what i really want to do is to make it show for each month the cases and for each case the vehicles.
1
10001
1000011
10002
1000021
1000022
2
10058
1000581
I tried to do something like this but it doesn't show correctly. If someone could help me with this i would be really thankfull.
<table border="1">
<tr>
<th>month</th>
<th>st_case</th>
<th>veh_id</th>
</tr>
<?php
// Loop on rows in the result set.
$currentmonth = 0;
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
if ($currentmonth != $row["month"])
{
echo "<tr>";
echo "<td>";
echo "<strong>".$row["month"]."</strong>";
echo "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<td>".$row["st_case"]."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>".$row["veh_id"]."</td>";
echo "</tr>";
$currentmonth = $row["month"];
}
pg_close($link);
?>
</table>
picture: http://i61.tinypic.com/2nb8vgl.png
$ret = pg_fetch_all($result);
$group = array();
foreach($ret as $v){
$group[$v['month']][$v['st_case']][] = $v['veh_id'];
}
foreach($group as $month=>$value){
echo $month."<br/>";
foreach($value as $st_case=>$v){
echo $st_case."<br/>";
foreach($v as $veh_id){
echo $veh_id."<br/>";
}
}
}
PS.then add some css to style your table
If you do not intend to display items in a table, do not use table
What you want is something like this:
<div class="result">
<div class="month_group">
<span class="month bold">1</span>
<div class="case_group">
<span class="case">10001</span>
<div class="veh_group">
<span class="veh_id">1000011</span>
</div>
<span class="case">10002</span>
<div class="veh_group">
<span class="veh_id">1000021</span>
<span class="veh_id">1000022</span>
</div>
</div>
</div>
<div class="month_group">
<span class="month">2</span>
<div class="case_group">
<span class="case">10058</span>
<div class="veh_group">
<span class="veh_id">1000081</span>
</div>
</div>
</div>
</div>
Then all that's left to do is applying simple css to give the classes some padding/margin.
HTML is a markup language. You structure the web page using the HTML tags. However, how it would look like depends more on css (which is why it's called Cascading Style Sheets).
Here's the rendering code. I have not tested it yet, and I have not touched PHP for sometime, but it should give you some general ideas:
echo "<div class=\"result\">";
for($ri = 0; $ri < $numrows; $ri++) {
$row = pg_fetch_array($result, $ri);
$month = $row["month"];
echo "<div class=\"month_group\">\n";
echo "<span class=\"month\">".$month."</span>\n";
echo "<div class=\"case_group\">\n";
for ($ci = $ri; $ci < $numrow; $ci++) {
if ($ci == $ri) {
$c_row = $row;
} else {
$c_row = pg_fetch_array($result, $ci);
}
if ($c_row["month"] != $month) {
// We have moved to another month
break;
}
$case = $c_row["st_case"];
echo "<span class=\"case\">".$case."</span>\n";
echo "<div class=\"veh_group\">\n";
for ($vi = $ci; $vi < $numrow; $vi++) {
if ($vi == $ci) {
$v_row = $c_row;
} else {
$v_row = pg_fetch_array($result, $vi);
}
if ($v_row["st_case"] != $case) {
// We have moved to another case
break;
}
$veh = $v_row["veh_id"];
echo "<span class=\"veh_id\">".$veh."</span>\n";
// we have already processed rows whose indexes are less or equal $vi
$ri = $vi;
}
echo "</div>";
}
echo "</div></div>";
}
Try this updated code
<table border="1">
<tr>
<th>month</th>
<th>st_case</th>
<th>veh_id</th>
</tr>
<?php
// Loop on rows in the result set.
$currentmonth = 0;
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
// Open the row
echo "<tr>";
echo "<td><strong>" . $row["month"] . "</strong></td>"; //open and close each column
echo "<td>".$row["st_case"]."</td>";
echo "<td>".$row["veh_id"]."</td>";
echo "</tr>"; //close the row
$currentmonth = $row["month"];
}
pg_close($link);
?>
</table>
You will also need to call the ORDER BY keyword in your MySQL statement to order by month.
Here is a simple tutorial on how to do this.
Here is a Demo of how it might look in your application.
Let me know if this helps and if i can be of any other help.

How to apply for loop to container in 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.

How to create a table in HTML using PHP

I have 5 pictures stored in a folder and their links stored on the database.
I want to put them in a table of three columns on each row.
<body>
<center>
<table border='1'>
<?php
$host="";
$username="";
$password="";
$db_name="fruits_db";
$tbl_name="fruits_tbl";
$connection=mysqli_connect("$host","$username","$password","$db_name");
if (mysqli_connect_errno())
{
echo "The application has failed to connect to the mysql database server: " .mysqli_connect_error();
}
$result = mysqli_query($connection, "SELECT * FROM fruits_tbl")or die("Error: " . mysqli_error($connection));
$num_rows=mysqli_num_rows($result);
$rows = $num_rows/3;
for($i=1; $i<=$rows ; $i++)
{
echo "<tr>";
for($j=1; $j<=3; $j++)
{
while($row = mysqli_fetch_array($result))
{
echo
("<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
mysqli_close($connection);
?>
</table>
</center>
</body>
</html>
The above code I created, contains two FOR loops. The script should count the number of rows in the table, and then divide by 3(the number of columns on each row in the HTML table).
I wonder where I'm going wrong wit this code.
With your while($row = mysqli_fetch_array($result)){} inside your 1st for loop it will run through all your rows, before the outside loop runs 2nd/3rd time.
Here is another way to do it -
$counter = 1;
// start 1st row
echo "<tr>";
while($row = mysqli_fetch_array($result)){
// if the 4th cell, end last row, and start new row
if ($counter%3==1){
echo "</tr><tr>";
}
echo
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>";
// increase the counter
$counter++;
}
// close the last row
echo "</tr>";
You're looping through all the results in the first table cell.
Try something like this instead:
for($i=1; $i<=$rows ; $i++) {
echo "<tr>";
for($j=1; $j<=3; $j++) {
$row = mysqli_fetch_array($result);
if ($row) {
echo(
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
If you just want to format the display with a new row after every 3 records, you could use the modulus operator:
$cntr = 0;
echo '<tr>';
while($row = mysqli_fetch_array($result)) {
$cntr++;
echo '
<td width="180px" height="200px">
<div class="fruit_image">
<img src="'.$row['fruit_image'].'" />
</div>
<div class="fruit_title">'.$row['fruit_name'].'</div>
</td>';
if ($cntr % 3 == 0 && $cntr != $num_rows)
echo '</tr><tr>';
}
echo '</tr>';
Keep in mind however that all the solutions presented so far may leave you with a last row with one or two td elements. You can fill this if you desire with empty <td> </td> columns.
print "<center><table border=1>
<tr>
<td>id</td>
<td>name</td>
<td>company</td>
<td>branch</td>
<td>job title</td>
<td>contact</td>
<td>email</td>
<td>mgs</td>
</tr>";
while($row=mysql_fetch_array($query))
{
print "<tr>";
for ($i=0;$i<=(count($row)/2);$i++)
{
print "<td>$row[$i]</td>";
} print"</tr>";
}
}
else{echo " <p>No Records Found</p>";}
<?php
function studentTable($name,$grade){
echo "<tr> <td>$name</td><td>$grade</td></tr>";
}
?>
<table style="width:100%" border="solid">
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
<?php studentTable("Sarah", 90) ?>

Categories