Put for loops inside a variable? - php

In all my years of writing PHP, I've never come across an occasion were I would need to put for loops inside a standard php variable.
The reason: I need to pass this variable through a JSON request.
See my current code below.
What I'm doing here is writing a script to generate a standard HTML table based on users requirements (e.g number of rows & columns). And I need to put all this HTML into a variable and pass the variable through a JSON request which then decodes and is displayed to the user.
Any advice/tips/tricks would be a huge help.
<?php
$trows = 5;
$tcolumns = 7;
echo "<table class='table table-striped table-bordered'>";
echo "<thead>";
echo "<tr>";
for ($th = 0; $th < $tcolumns; $th++){echo '<th>[HEADER]</th>';
};
echo "</tr>";
echo "</thead>";
echo "<tbody>";
for ($tr = 0; $tr < $trows; $tr++){ echo '<tr>';
for ($td = 0; $td < $tcolumns; $td++){echo '<td>[CONTENT]</td>';
};
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>

<?php
$trows = 5;
$tcolumns = 7;
$result = "";
$result .= "<table class='table table-striped table-bordered'>";
$result .= "<thead>";
$result .= "<tr>";
for ($th = 0; $th < $tcolumns; $th++){$result .= '<th>[HEADER]</th>';
};
$result .= "</tr>";
$result .= "</thead>";
$result .= "<tbody>";
for ($tr = 0; $tr < $trows; $tr++){$result .= '<tr>';
for ($td = 0; $td < $tcolumns; $td++){$result .= '<td>[CONTENT]</td>';
};
$result .= "</tr>";
}
$result .= "</tbody>";
$result .= "</table>";
?>

Create a variable, say $output, to store the html table in.
After you have finished building the table you can do whatever you choose with it. Print it out, use it in another variable to build a json object.
See below
$output = "<table class='table table-striped table-bordered'>";
$output .= "<thead>";
$output .= "<tr>";
for ($th = 0; $th < $tcolumns; $th++){
$output .= '<th>[HEADER]</th>';
};
$output .= "</tr>";
$output .= "</thead>";
$output .= "<tbody>";
for ($tr = 0; $tr < $trows; $tr++){
$output .= '<tr>';
for ($td = 0; $td < $tcolumns; $td++){
$output .= '<td>[CONTENT]</td>';
};
$output .= "</tr>";
}
$output .= "</tbody>";
$output .= "</table>";
echo $output;

Use output buffering:
// Start output buffering
ob_start();
/*
Your code here
*/
// Fetch buffered output and save to variable
$content = ob_get_contents();
// End output buffering, flush buffer. This outputs the buffer content
ob_end_clean();
// If you don't want the buffer to be output use this
// ob_end_clean();

Related

How to parse data returned from a text file into an HTML table using PHP

I am returning book data (title, ISBN, author) information from a text file into an array. I am able to pull the data from the text file, read it it and display it as an array but how do I display this information into an HTML table? The HTML table needs to be created using PHP. Where I print the $book in the foreach, all the books are returned as an array but How do I output them in an HTML table created using solely php. I am NOT receiving errors, just need to know how to insert the return the data into an HTML table using PHP.
? Here is what I have so far
PHP
<?php
$infoArray = array(); //New empty array
$filename = 'books.txt';
$lines = count(file($filename));
$fp = fopen($filename, 'r');
for($ii = 1; $ii <= $lines; $ii++){
$line = fgets($fp);
array_push($infoArray, $line);
}
fclose($fp);
sort($infoArray);
list($title, $ISBN, $Author) = explode('*', $line);
$cntr = 0;
foreach ($dataReturned as $line){
print $line;
print '<br>';
}
This is what I want to print out as but it is not working. I am unsure how and where to incorporate this code.
$htmltable = "<table border='1'>";
$htmltable .= "<tr>";
$htmltable .= "<th>Title</th>";
$htmltable .= "<th>ISBN</th>";
$htmltable .= "<th>Author</th>";
$htmltable .= "</tr>";
$htmltable .= "<tr $style>";
$htmltable .= "<td>".$title."</td>";
$htmltable .= "<td>".$ISBN."</td>";
$htmltable .= "<td>".$Author."</td>";
$htmltable .= "</tr>\n";
print $htmltable;
TEXT FILE INFO
These are a few lines being pulled from the text file.
Healthy Living*1-4988-9986-x*Smith
How to Live Life*1-5698-9865-x*Romero
Better Speech*1-6996-9989-x*Grimes
This is one possible approach:
PHP:
<?php
#
$filename = 'file-books.txt';
$file = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
#
echo "<table border='1'>";
echo "<thead>";
echo "<tr>";
echo "<th>Title</th>";
echo "<th>ISBN</th>";
echo "<th>Author</th>";
echo "</tr>";
echo "</thead>";
# Extract the lines.
echo "<tbody>";
foreach ($file as $row) {
$fields = explode('*', $row);
echo "<tr>";
echo "<td>".$fields[0]."</td>";
echo "<td>".$fields[1]."</td>";
echo "<td>".$fields[2]."</td>";
echo "</tr>";
}
#
echo "</tbody>";
echo "</table>";
?>
Text file:
Healthy Living*1-4988-9986-x*Smith
How to Live Life*1-5698-9865-x*Romero
Better Speech*1-6996-9989-x*Grimes
Just reading the file as a CSV (although with a * delimeter)...
$fp = fopen($filename, 'r');
$style = "";
$htmltable = "<table border='1'>";
$htmltable .= "<tr>";
$htmltable .= "<th>Title</th>";
$htmltable .= "<th>ISBN</th>";
$htmltable .= "<th>Author</th>";
$htmltable .= "</tr>";
while ( $row = fgetcsv($fp, null, "*")) {
$htmltable .= "<tr $style>";
$htmltable .= "<td>".$row[0]."</td>";
$htmltable .= "<td>".$row[1]."</td>";
$htmltable .= "<td>".$row[2]."</td>";
$htmltable .= "</tr>\n";
}
$htmltable .= "</table>\n";
fclose($fp);
echo $htmltable;
$html_table = '';
$html_table .= '<table>';
$html_table .= '<thead>';
$html_table .= '<th>Title</th>';
$html_table .= '<th>ISBN</th>';
$html_table .= '<th>Author</th>';
$html_table .= '</thead>';
$html_table .= '<tbody>';
foreach ($dataReturned as $line){
$html_table .= '<tr>';
$html_table .= "<th>$line[0]</th>";
$html_table .= '<th>$line[1]</th>';
$html_table .= '<th>$line[2]</th>';
$html_table .= '</tr>';
}
$html_table .= '</tbody>';
$html_table .= '</table>';
echo $html_table;
--- Sorry for creating this as new answer, cant edit my last comment with code formatting. ---
Can you show us an example of what data the variable $line contains? Because if its an array, you need to do another foreach inside the "foreach ($dataReturned as $line)" loop to get the data inside the variable $line or if its an object, try to get the respective attribute.
After knowing what you have, try to create an empty variable which is gonna contain all your HTML and use your foreach loop to append the columns and rows.
Are you sure that you have data in the array ? I was checking your code and look good, however you can use "echo" for print data in the browser.
You can test your code in this web page http://phptester.net/-
i hope that it could help you.

PHP While Loops Table Mysqli Results

I'm about month and a half into PHP. I tried to make function for fetching results from find_all_subjects():
function find_all_subjects() {
global $dbconnect;
$q = "SELECT * FROM subjects ORDER BY id ASC";
$subject_set = mysqli_query($dbconnect, $q);
confirm_query($subject_set);
return $subject_set;
}
and then making a new function which will loop the result in table rows. The problem is it loops just one result... when I did it with <ul> and <li> it worked fine but it doesn't seem to work when doing it with the table. My table core tags are in another document. So it's not that...
function navigacija() {
$s = find_all_subjects();
while($subjects = mysqli_fetch_assoc($s)) {
$out = "<tr>";
// Ime Teme
$out .= "<td width='25%' height='40'> <a href=\"admin_content.php?subject=" . urlencode($subjects['id']) . "\">";
$out .= $subjects['menu_name'];
$out .= "</a></td>";
// Vidljiva
if($subjects['visible'] == 1) {
$subjects['visible'] = 'DA';
} else {
$subjects['visible'] = 'NE';
}
$out .= "<td width='25%' height='40'><p align=\"center\">DA / NE";
$out .= "</p></td>";
// Broj Strana
$out .= "<td width='25%' height='40'>";
$pages_set = find_sub_from_pages($subjects['id']);
while($pages = mysqli_fetch_assoc($pages_set)) {
$out .= "" . $pages['menu_name'] . "";
$out .= "</td>";
}
// Vidljiva
$out .= "<td align=\"center\" width='25%' height='40'>";
$out .= "<img width=\"17px\" height=\"17px\" src=\"st/img/ic-arup.png\">
</img> <img width=\"17px\" height=\"17px\" src=\"st/img/ic-ardown.png\"></img> ";
$out .= "</td>";
$out .= "</tr>";
}
return $out;
}
the problem is that you reset
$out = "<tr>";
every time in the loop.
change this line to
$out .= "<tr>";
and only put declaration out of the loop
$out = "";

How to add a header to a table, and how to add a border in php

I have been writing queries to get information from a table in php. I can print out the information, but it does not look pretty at all. I was wondering how I could make the tables that are outputted better by having black lines as the borders of each cell, and also how to add a column header to my tables. Right now my output for my first query looks like this:
Massachusetts 152082
Missouri 151580
Illinois 111454
And I want my output to look like this (I also want each cell to have a black border):
district population
Massachusetts 152082
Missouri 151580
Illinois 111454
Here is the code for when I print out my table. I dont think you will need any code from the queries so I wont post that. Thanks for the help in advance.
echo "<table>\n";
while($line = pg_fetch_array($result, null, PGSQL_ASSOC)){
echo "\t<tr>\n";
foreach($line as $col_value){
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
try this:
//table header
$table = "<table border='1px'>";
$table .= "<thead>";
$table .= "<tr>";
$i = pg_num_fields($result);
for ($j = 0; $j < $i; $j++) {
$fieldname = pg_field_name($result, $j);
$table .= "<th>$fieldname</th>";
}
$table .= "</tr>";
//table body
$table .= "<tbody>";
while($row = pg_fetch_assoc($result))
{
$table .= "<tr>";
foreach ($row as $key => $value)
{
$table .= "<td>$value</td>";
}
$table .= "</tr>";
}
$table .= "</tbody>";
$table .= "</table>";
//echo table
echo $table;

Populate an html table columwise with mysql data

I have a MySQL query that returns data using PHP.
My problem is that I need to populate my html table (with 3 columns) with the data returned by the query but the data should be populated Columnwise.
Like first the first column should be populated .. then the second and finally the third one.
Also I would like to know that is it possible to do so for an unlimited set of data?
Following the screen shot of the desired layout
you can use while.
<table>
$sql=mysql_query("select * from table");
while($s=mysql_fetch_array($sql))
{
$x=$s["x"];
<tr>
<td ><?php echo $x; ?></td>
<td ><?php echo $y; ?></td>
<td ><?php echo $z; ?></td>
</tr>
}
</table>
guybennet's answer is correct but if you want it to work for an unlimited amount of columns you could do this: (I also threw in some column headers for readability)
echo '<table>';
$counter = 0;
$result = mysql_query("select * from table");
while($row = mysql_fetch_array($result)) {
$counter++;
if($counter == 1) {
echo '<tr>';
foreach($row as $key => $val) {
echo "<th>$key</th>";
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
echo '</table>';
Also of course you should use mysqli or PDO I'm just showing a quick example.
If you don't care about how it's organized, you can try something like this:
echo "<table><tr>";
$i=0;
while($row = mysql_fetch_array($sql))
{
echo "<td>".$row[0]."</td>\n";
$i++;
if($i==3)
{
echo "</tr>\n<tr>";
$i=0;
}
}
echo "</tr></table>";
Otherwise, I'd suggest putting it all into an array and then putting it into the table.
$data = array();
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
$itemsAmount = count($data);
$ceilAmount = ($itemsAmount - $itemsAmount % 3) / 3;
$lastAmount = $itemsAmount % 3;
$firstArray = array_slice($data, 0, $itemsAmount);
$secondArray = array_slice($data, 0, $itemsAmount*2);
$thirdArray = array_slice($data, 0, $lastAmount);
$output = "<table>";
foreach ($data as $key => $value) {
$output .= "<tr>";
$output .= "<td>" . $firstArray[$key][0] . "</td>";
$output .= "<td>" . $secondArray[$key][0] . "</td>";
if (empty($thirdArray[$key])) {
$str = '';
} else {
$str = $thirdArray[$key][0];
}
$output .= "<td>" . $str . "</td>";
$output .= "</tr>";
}
$output .= "</table>";
echo $output;
You need to check all the results returned, then print them as you won't print in order:
First get an array with all the results
<?php
$sql= mysql_query('SELECT * FROM table');
$num= mysql_affected_rows($sql);
$items = array();
$i=0;
while($item=mysql_fetch_array($sql)){
$items[++$i]=$item['data'];
}
Now start printing
int $num_rows;
$num_rows=$num%3;
echo '<table>';
for ($i=0;$i<$num_rows;$i++){
echo '<tr>';
for ($j=0;$j<2,$j++){
$n=$i+1+($j*$num_rows);
if($items[$n]!==null)
echo '<td>'.$items[$n].'</td>';
else
echo '<td></td>';
}echo '</tr>';
}echo'</table>';
?>

display only 3 foreach result per row

i have script as follows
$output="<table class='products'><tr>";
while($info = mysql_fetch_array( $data )) {
//Outputs the image and other data
$output.= "<td>
<img src=http://localhost/zack/sqlphotostore/images/" .$info['photo'] ." width=323px ></img>
<b>Name:</b> ".$info['name'] . "
<b>Email:</b> ".$info['email'] . "
<b>Phone:</b> ".$info['phone'] . "</td> ";
}
$output.="<tr></table>";
print $output;
?>
it shows all results in long horizontal line how do i break the results so that they show
in new row after 3 count.
Keep a counter, and output a new table row every 3 images
$output="<table class='products'>";
$counter = 0;
while($info = mysql_fetch_array( $data ))
{
if( $counter % 3 == 0 )
$output .= '<tr>';
$output .= "<td>";
$output .= "<img src=http://localhost/zack/sqlphotostore/images/".$info['photo'] ." width=323px ></img>";
$output .= "<b>Name:</b> ".$info['name'];
$output .= "<b>Email:</b> ".$info['email'];
$output .= "<b>Phone:</b> ".$info['phone']."</td> ";
if( $counter % 3 == 0)
$output .= "</tr>";
$counter++;
}
$output.="</table>";
print $output;
?>
Add a counter and start a new row every time it reaches a multiple of 3.
$counter = 0;
while($info = mysql_fetch_array($data)) {
if ($counter++ % 3 == 0) {
if ($counter > 0) {
$output .= "</tr>";
}
$output .= "<tr>";
}
// stuff
}
if ($counter > 0) {
$output .= "</tr>";
}
$output .= "</table>";
Please note: It may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.

Categories