PHP Variable in a string in a string - php

I am attempting to echo a sting containing a variable already stored in a variable. Essentially I am building a class that can dynamically build tables based on a changing number of columns. I need get my db field names into the foreach loop before the foreach loop that has my db results, and then iterate over them in the loop. The problem is I have to store them in a loop prior to the db results loop; which is not recognizing it as a variable and just giving me a plain text '$row['myVar']'.
How can I get this to recognize the variable in the second loop?
$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlVarNames as $columnVar) {
$finalColumnVars .= '<td>\'. $row[\''.$columnVar.'\'] .\'</td>';
}
and then into my second loop
foreach ($sqlResult as $row) {
echo '<tr>';
echo $finalColumnVars;
echo '</tr>';
}
I tried all sorts of escape sequences on my $finalColumnVars and can't seem to get it to output the variable instead on plain text.
Here is what I get with the above code
<td>'. $row['client_name'] .'</td>
Is this possible?

$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlVarNames as $columnVar) {
$finalColumnVars .= '<td>'.$row[$columnVar].'</td>';
}

here is how you can merge these two loop and get the desired.
$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlResult as $row) {
echo '<tr>';
foreach ($sqlVarNames as $columnVar) {
echo '<td>'. $row[$columnVar] .'</td>';
}
echo '</tr>';
}

Related

Get SQLite Table Data into HTML Table

I have an SQLite database and using PHP to serve up and interact the data with.
I am trying to build an HTML table with for each SQLite table columns as the HTML Table Columns and then for each row in the SQLite table render as a for each row in the HTML table.
Issue is that each sql row data is only rendered into one html table row (with current code) (should be for each row) question would be how I go about getting the sql row data into array for looping through to render html table rows.
Currently I have;
PHP get the SQL Columns into the HTML table & SQl Row data(foreach) into HTML Table Rows (foreach)
//get table count
$countTable = $dbConnect->querySingle("SELECT COUNT(*) as count FROM ".$table['name']."");
if($countTable){
//data exists, do work
//new query to get table data
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
//init arrays
$dataColumns = array();
$dataRows = array();
while($row = $query->fetchArray(SQLITE3_ASSOC))
{
//add columns to array, checking if value exists
foreach($row as $key => $value)
{
if(in_array(''.$key.'', $dataColumns)){
//column already in array, dont add again.
}else{
//column not in array, add it.
$dataColumns[]=array(
'column'=>$key
);
}
//while in this foreach do I add the row values to an array or do it again outside this loop?
//below does not work, only adds to the one array item and renders one HTML Table row with multiple SQL Table row values
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
}
}
//build HTML table
echo '<div class="table-responsive"><table class="table"><thead><tr>';
//build columns from array... works
foreach($dataColumns as $dataColumn){
echo '<th>'.$dataColumn['column'].'</th>';
}
//close table column headers 7 start HTML table body...
echo '</tr></thead><tbody>';
//Issue is here, how do I get the each row (value is either null or not null) to
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['row_item'].'</td>';
}
echo '</tr>';
//close table body & table...
echo '</tbody></table></div>';
}else{
//table has no data
echo 'no data in the selected table';
}
I rewrote this to do it all in one loop like this.
$firstRow = true;
echo '<div class="table-responsive"><table class="table">';
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
if ($firstRow) {
echo '<thead><tr>';
foreach ($row as $key => $value) {
echo '<th>'.$key.'</th>';
}
echo '</tr></thead>';
echo '<tbody>';
$firstRow = false;
}
echo '<tr>';
foreach ($row as $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table></div>';
You might find it clearer to read? It also avoids building an array of all the dataRows in memory.
Try to replace
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
with
$dataRows[]=$row;
Put this line at first line inside your while loop (or general outside the foreach loop over your columns), because adding a row is not connected analyzing your columns.
Then, in your output foreach, you should find the rows with all columns selected from your database query inside $dataRow (here symbolized with column1, column2, …):
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['column1'].'</td>';
echo '<td>'.$dataRow['column2'].'</td>';
echo '<td>'.$dataRow['column3'].'</td>';
echo '<td>'.$dataRow['column4'].'</td>';
echo '<td>'.$dataRow['column5'].'</td>';
echo '<td>'.$dataRow['column6'].'</td>';
echo '<td>'.$dataRow['column7'].'</td>';
// etc.
}
echo '</tr>';
After all your code should look like this (a bit simplified):
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
$dataColumns = array();
$dataRows = array();
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$dataRows[] = $row;
foreach ($row as $key => $value) {
//Bilding $dataColumns, see Question
}
}
echo '<div class="table-responsive"><table class="table"><thead><tr>';
foreach ($dataColumns as $dataColumn) {
echo '<th>'.$dataColumn['column'].'</th>';
}
echo '</tr></thead><tbody>';
echo '<tr>';
foreach ($dataRows as $dataRow) {
foreach ($dataRow as $columnName => $columnValue) {
echo '<td>'.$columnValue.'</td>';
}
}
echo '</tr>';
echo '</tbody></table></div>';
Thanks to akrys
in the while loop, but outside the foreach column loop;
//$dataRows = array();
$dataRows[]=$row;
and in the building of the HTML Table;
foreach($dataRows as $dataRow){
echo '<tr>';
foreach($dataRow as $key => $value){echo '<td>'.$value.'</td>';}
echo '</tr>';
}

PHP Simple HTML DOM - Table row by row

I currently can parse a html table using simplehtmldom. The problem I have is that the program prints the entire table in one block.
How would I print row by row?
How could I limit the rows to just the ones with times? (see http://www.masjid-umar.org/downloads/timetable_apr.htm)
Below is the code I am currently using:
<?php
include('simple_html_dom.php');
$dom = file_get_html('http://www.masjid-umar.org/downloads/timetable_apr.htm');
$table = $dom->find('table',0);
$rows = $table->children(0)->children();
foreach($rows as $row)
foreach($row->children() as $column) {{
if(!empty($column->innertext)) {
echo $column->innertext . '<br />' . PHP_EOL;
}
}
}
The following is printed http://pastebin.com/cAMECf9f
You could store the individual cells in a multi-dimensional array and loop through that to output it, but if you just want the table, you can skip the loops and do something like:
$table = $dom->find('table',0);
echo $table->save();
Just search for the times:
foreach($dom->find('tr') as $tr){
if(!preg_match('/\d+\.\d+/', $tr->text())) continue;
echo $tr->text() . "\n";
}

PHP table from explode array

I have data like this:
something something_description, something2 something2_description, something3 something3_description...
And now I need with PHP to get table as:
<tr><td>something</td><td>something_description</td></tr>
<tr><td>something2</td><td>something2_decription</td></tr>
I don't know how many "something" and "something_decriptions" will it be so I need to set some loop.
for now I have this code:
$data = explode(',',$query);
from that I will get array like:
[0] => something something_description
Now how can I put this into table?
On net I found some examples for sorting array to table, but this is with one more "explode" inside "explode"
I could use some help.
Probably you are looking for this:
$data = explode(',',$query);
echo '<table>';
foreach($data as $row){
echo '<tr>';
$row = explode(' ',$row);
foreach($row as $cell){
echo '<td>';
echo $cell;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
Try this:
echo "<table><tr>".implode("</tr><tr>",array_map(function($a) {return "<td>".implode("</td><td>",explode(" ",trim($a)))."</td>";},explode(",",$query)))."</tr></table>";
One-liner ftw :p

How to stop a while loop from running infinatly by making it stop when there are no more values in the array

I am trying to make pull key => value pairs out of an array by using a do { ....} while {there are values left inside the array.
I am using a function to query mysql for and then to insert all the values inside an array
function table_array($query) {
$table_array = array();
$data_fetched = false;
while ($array = mysql_fetch_assoc($query)) {
if (!$data_fetched) {
foreach ($array as $key => $value) {
$table_array[$key] = $value;
//$data_fetched = true;
}
}
}
return $table_array;
}
and then i am using another loop to extract the data from the array
function get_table($table_array) {
$header_written = false;
echo "<table border=1>";
if ($table_array) {
do {
echo "<tr>";
foreach ($table_array as $columns => $values) {
echo "<td> {$values} </td>";
}
echo "</tr>";
}while ($table_array);
}
echo "</table>";
}
However this causing my loop to run infinitely , why can't i use it just as though i would be doing while mysql_fetch_assoc is true.
I tried using a flag but that will stop it running after only one record is being extracted.
What you really need here are two foreach loops. The outer iterates over rows, and the inner iterates over columns:
echo "<table>";
// Iterates over rows
foreach ($table_array as $row) {
echo "<tr>";
// Iterates over columns (table cells)
foreach ($row as $col=>$value) {
echo "<td>{$value}</td>";
}
echo "</tr>";
}
echo "</table>";
Though your fetching process works, it can be simplified and improved. You don't need a foreach to assign columns to your $table_array. You can simply append the whole fetched row using the [] syntax. Not sure what the purpose of $data_fetched was, so I removed that as well
while ($array = mysql_fetch_assoc($query)) {
// Use the [] syntax to append the whole row onto $table_array
// No need to add each column of the fetched row separately
$table_array[] = $array;
}
Finally, the reason it didn't work the way you setup your do-while is that iterating over a regular array is not similar to fetching from a MySQL result set. The fetch calls will eventually return FALSE when no rows remain. Unless you are actively removing elements from an array while iterating over it, and eventually deleting the empty array, it will always evaluate to a boolean TRUE.
You need to use either foreach($array as $key => $value){ ... } or do{ ... } while ($array).
You should not use both, as you only have one set of data to loop over. I would stick with foreach as it is safer, and can do exactly what you need.
If you feel you need to use a do/while, then you need to pop a value off the $table_array each time you are inside the loop. This way, the $table_array will become empty at some point. Currently, in your code, the $table_array is always full so the while loop continues endlessly.

importing and mapping data from source file to HTML tables

php newbie here..I need some PHP help ideas/examples on how to import data from a delimited text file and map them into html tables. The data should populate and be mapped under its proper header. There are instances also where each record doesn't have all the values and if no data, then we can leave it null (See sample records). I would also create a table row entry for each record.
For example, the input/source file has these entries: (they are prefixed by a number to represent the header in the html table. So data from "1-MyServer" is "server4.mra.dev.pp1" and should be under table header "Server" for example. There are instances also where the record doesn't have all the values (1-7) (See below):
1-MyServer=server4.mra.dev.pp1;2-MyLogdate=Wed Aug 11 2010;3-MyDataset=dbip.pp1;4-MyStartTime=01:00:03;5-MyDuration=00:36:09;6-MySize=41.54 GB;7-MyStatus=Succeeded;
1-MyServer=server9.mra.dev.kul;2-MyLogdate=Wed Aug 11 2010;3-MyDataset=gls202.kul_lvm;5-MyDuration=06:20:33;7-MyStatus=Succeeded;
1-MyServer=server9.mra.dev.kul;2-MyLogdate=Wed Aug 11 2010;3-MyDataset=gls101.aie_lvm;4-MyStartTime=01:00:02;
Here is a copy of my html table that I would need it to map it too:
(Also, I would not have to populate record for "2-MyLogdate" into a header)
<table id="stats">
tr>
<th>Server</th>
<th>Set</th>
<th>Start</th>
<th>Duration</th>
<th>Size</th>
<th>Status</th>
</tr>
<tr>
<td>server4.mel.dev.sp1</td>
<td>dbip.sp1</td>
<td>01:00:03</td>
<td>00:36:09</td>
<td>41.54 GB</td>
<td>Succeeded</td>
</tr>
</table>
So what I really need is a system to map these appropriately.
How would I write this in php?? Thanks!
It's all about finding the patterns in your files. In your example, it's rather easy:
[number]-[column name]=[value];
The main problem I see is that you have redundant information: the number of the column, and the columns themselves, which are repeated for every row. You can parse them away, though. It depends on what you expect from your program: will the columns order always be the same? Will there always be the same columns? How should you react to unknown columns?
Here's a quick example of what you could do, using regular expressions. This example assumes that column names are all the same, and that you want to display them all, and that they'll always be in the same order. In other words, I'm doing it the easy way.
$data = array();
$lines = file("my/log/file.log");
// this will parse every line into an associative array, discarding the header number
foreach ($lines as $line)
{
// populate $matches with arrays where indices are as follows:
// 0: the whole string (0-Foo=bar;)
// 1: the column number (0)
// 2: the column name (Foo)
// 3: the value (Bar)
preg_match_all("/([0-9])-([^=]+)=([^;]+);/", $line, $matches, PREG_SET_ORDER);
$lineData = array();
foreach ($matches as $information)
$lineData[$information[2]] = $information[3];
$data[] = $lineData;
}
$keys = array_keys($data[0]); // you can also set this yourself
// for instance, $keys = array('MyServer', 'MyDataset'); would only display those two columns
echo '<table><tr>';
foreach ($keys as $column)
echo '<th>' . $column . '</th>';
echo '</tr>';
foreach ($data as $row)
{
echo '<tr>';
foreach ($keys as $column)
echo '<td>' . (isset($row[$column]) ? $row[$column] : '') . '</td>';
echo '</tr>';
}
echo '</table>';
something like this
$logarr = file("log.txt");
foreach ($logarr as $s) {
$s = str_replace(";","&",$s);
$a = array();
parse_str($s,$a);
echo "<tr>\n";
if (isset($a['1-MyServer'])) echo $a['1-MyServer']; else echo " "
if (isset($a['2-MyLogdate'])) echo $a['2-MyLogdate']; else echo " "
// and so on
echo "</tr>\n";
}

Categories