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";
}
Related
This question already has an answer here:
How to get column names from PDO's fetchAll result?
(1 answer)
Closed 2 years ago.
The following code works perfectly well unless there is only one result, in which case only the <tr> containing the column names displays in the web page. Further, a search for the name 'Bracker' produces the result as described above but a search for 'Bra' works correctly while 'Brac' does not. The same does not apply to the name 'Dawe' which, if there is only one result, only appears amongst many others when a search for 'Da' is undertaken.
<?php
include 'connect.php';
if (isset($_POST['submit-keyword'])) {
$keyword = ($_POST['keyword']);
$qry = "SELECT * FROM Ely_NBR WHERE Founder LIKE ? ORDER BY DATE";
$stmt = $con->prepare($qry);
$stmt->execute(["%$keyword%"]);
print "<table>";
$result = ($stmt);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
} // end foreach
print " </tr>";
//second query gets the data
$data = ($stmt);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} // end field loop
print " </tr>";
} // end record loop
print "</table>";
}
?>
You are using your first result row to display the column headings. When you call PDOStatement::fetch() it moves its internal cursor on the result set.
Therefore your loop to display the data starts printing the results from the 2nd row.
See PDOStatement::fetch() documentation: Fetches the next row from a result set.
If you want to get the column names you may want to look at:
PDOStatement::columnCount()
PDOStatement::getColumnMeta()
And print headings like this:
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$columnInfos = $stmt->getColumnMeta($i);
echo '<th>' . $columnInfos['name'] . '</th>';
}
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>';
}
Basically what I'm doing is storing everything from my table into an array.
After that I go through it and select row by row and assign it to an array.
Then it goes through that array and puts it in the table, cell by cell, in a single row.
Now the last column of my table are links and they are the fourth and last column in the table and in the database. They're, just like they should, showing up as plain text, but I'd rather have them clickable (For ease of use).
Since the entire table (Except for the, in this case, 4 header items) is created by php code I would have no clue on how to change just the last bit to be a link.
Help would really be appreciated!
Code:
$sql = "SELECT * FROM Future_Mods";
$result = mysqli_query($conn, $sql) or die (mysql_error());
echo "<table>";
echo "<tr>
<th>ID</th>
<th>Mod</th>
<th>Is Available</th>
<th>Has Been Added</th>
<th>Reason</th>
</tr>";
for($i = 0; $i < mysqli_num_rows($result); $i++) {
echo "<tr>";
$row_array = mysqli_fetch_row($result);
for ($j = 0; $j < mysqli_num_fields($result); $j++) {
echo "<td>" .$row_array[$j]. "</td>\n";
}
}
echo "</table>";
Relatively simple:
while ($row = mysqlI_fetch_row($result)) {
end($row); // move array pointer to end of array
$key = key($row); // get key of current pointer element
// update last item to be a link
$row[$key] = '', $row[$key], '';
// dump out array as table cells
echo '<td>', implode('</td><td>', $row), '<td>';
}
This is a question of HTML formatting for your result set table.
If you happen to have a php variable $s that you are sure contains a URL, you can display the URL and make it clickable with php code like this:
echo sprintf ('$1', $s);
For example if $s has the value http://stackoverflow.com/ this will yield the HTML text
http://stackoverflow.com/
One of your $row items will contain that URL. So you can render it with this sort of patten.
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";
}
I have a MySQL database with 35 different columns labeled 1-35. The data is displayed in a dynamic table. I am looking for the PHP code that would allow me to apply a CSS class to specific cells based on what is returned inside them.
EXAMPLE: Column 1 can return either TRUE or FALSE value. If a TRUE value is returned, I want to give that cell a different background color, or highlight it.
I have the CSS class as:
.highlight {
background-color: #FC0;
}
After the CSS class has then been applied to the specific cells from columns 1-35, I would like the PHP code that can total the number of highlighted cells in the column labeled TOTAL.
Can't seem to find the PHP code to tie all this together. If someone could advise, I'd be very grateful.
<td class="<?php if ($row['item'] == TRUE)
{
echo 'highlight';
$highlights++;
}
else
{
echo 'no_highlight';
}
?>"><?php echo $row['item'];?></td>
and then...
<td id="totalHighlights"><?php echo $highlights;?></td>
EDIT: Sample code...
<?php
//We've queried the database and passed the results into $result via mysql_fetch_assoc().
while ($row = $result)
{
//Clear highlights and values arrays for each row.
$highlights = array();
$values = array();
foreach($row as $entry)
{
if ($entry == TRUE)
{
//Put a truthy value into highlights array.
array_push($highlights, 1);
}
else
{
//Put a falsey value into highlights array.
array_push($highlights, 0);
}
//Push actual field value to values array.
array_push($values, $entry);
}
echo '<tr class="row">';
//Create cell with total highlights per row using the array_sum() of highlights.
echo '<td class="row_total_highlights">'.array_sum($highlights).'</td>';
//Create each value cell and populate them with each field value from values array.
$i = 0;
foreach ($values as $value)
{
echo '<td class="entry ';
echo ($highlights[$i] == 1 ? 'trueClass' : 'falseClass');
echo '">'.$value.'</td>';
$i++;
}
echo '</tr>';
}