PHP AND MySQL - Entire table column needs links instead of plain text - php

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.

Related

Why does only the table head display? [duplicate]

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

PHP / MySQL - how to transpose data (columns into rows) with dynamic column names into a table

I know there are other questions/answers about this sort of thing, but it took me a while to figure this specifically out, so I figured I'd share it with the community, as likely there are others who could benefit.
I had put together code like the following, which worked fine, but if you needed to add a column, meant adding the name 4 times before you even got to adding it where you wanted in the table:
<?php
// Prepare statement & retreive data from database
$sql_retreive = $con->prepare("
SELECT widget_id
, widget_name
, widget_price
, widget_upc
, widget_color
FROM widgets
WHERE widget_price > ?
");
$bind_process = $sql_retreive->bind_param('d',$price);
$sql_retreive->execute();
$result = $sql_retreive->get_result();
// Initiate arrays to place variables from query in order to transpose data from database
$widget_id = [];
$widget_name = [];
$widget_price = [];
$widget_upc = [];
$widget_color = [];
// If there are results, fetch values for each row and add values to each corresponding array
if($result->num_rows > 0 ){
while($row=$result->fetch_assoc()){
$widget_id[] = $row['widget_id'];
$widget_name[] = $row['widget_name'];
$widget_price[] = $row['widget_price'];
$widget_upc[] = $row['widget_upc'];
$widget_color[] = $row['widget_color'];
} // end of while
} // end of if num_rows > 0
// Build dynamic table with results transposed
echo "<table class='table'><thead>";
echo "<tr><th>Widgets</th>"; for ($i=0; $i<count($crop_name);$i++) {echo "<th>".$widget_name[$i]." (".$widget_id[$i].")</th>";}
echo "</tr></thead><tbody>";
echo "<tr><td>widget_price</td>"; for ($i=0; $i<count($widget_price);$i++) {echo "<td>".$widget_price[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_upc</td>"; for ($i=0; $i<count($widget_upc);$i++) {echo "<td>".$widget_upc[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_color</td>"; for ($i=0; $i<count($widget_color);$i++) {echo "<td>".$widget_color[$i]."</td>";} echo "</tr>";
echo "</tbody></table>";
?>
So I wanted to figure out a better way... see my answer below...
After spending a while working on it, I came up with this:
<?php
// Prepare statement & retreive data from database
$sql_retreive = $con->prepare("SELECT widget_id, widget_name, widget_price, widget_upc, widget_color FROM widgets WHERE widget_price > ?");
$bind_process = $sql_retreive->bind_param('d',$price);
$sql_retreive->execute();
$result = $sql_retreive->get_result();
if($result->num_rows > 0 ){ // If there are results, fetch values for each row and add values to each corresponding array
// Initiate an array for each field specified, in which to place variables from query, in order to transpose data from database
for($i = 0; $i < mysqli_num_fields($result); $i++) { // loop through fields
$field_info = mysqli_fetch_field($result); // for each, retreive the field info
$column = $field_info->name; // retreive the field name from the field info
$$column = []; // note double $$, create a blank array using the field name, will loop through for each
} // end of for loop
while($row=$result->fetch_assoc()){ // for each row of responses, place the data into the above created arrays
$field_info = mysqli_fetch_fields($result); // retreive the field info
foreach ($field_info as $field_value) { // for each, retreive the field info
$column = $field_value->name; // retreive the field name from the field info
$$column[] = $row[$column]; // note double $$, using the array (which uses the field name), place the row data in, and loop through for each
} // end of foreach loop
} // end of while
} // end of if num_rows > 0
// Build dynamic table with results transposed
echo "<table class='table'><thead>";
echo "<tr><th>Widgets</th>"; for ($i=0; $i<count($crop_name);$i++) {echo "<th>".$widget_name[$i]." (".$widget_id[$i].")</th>";}
echo "</tr></thead><tbody>";
echo "<tr><td>widget_price</td>"; for ($i=0; $i<count($widget_price);$i++) {echo "<td>".$widget_price[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_upc</td>"; for ($i=0; $i<count($widget_upc);$i++) {echo "<td>".$widget_upc[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_color</td>"; for ($i=0; $i<count($widget_color);$i++) {echo "<td>".$widget_color[$i]."</td>";} echo "</tr>";
echo "</tbody></table>";
?>
This enables you to just add the column/field name into the query, and then use the values where you want in the table.
Please upvote if you find this helpful!

SQL db row,1 cell containing multiple image locations, query

How can I process a sql cell ($afbeeldingen) containing multiple image locations?
The vehicle table holds the column "images"(or in dutch language "afbeeldingen"), and for one vehicle there can be multiple imagelinks in "images", urls are seperated with a ","
I would like to output
<img src=imagelocation>
for each location stored in the single cell.
function toon_voertuigen()
{
include ('dbconn.php');
$query = "SELECT * FROM vehicles";
$result = mysqli_query($con, $query) or die("Couldn’t execute query.");
$nrows = mysqli_num_rows($result);
echo "<table>";
for ($i = 0; $i < $nrows; $i++)
{
$n = $i + 1; //add 1 so numbers don’t start with 0
$row = mysqli_fetch_assoc($result);
extract($row);
echo "<tr>\n
<td>$n.</td>\n
<td>
$images //Contains multiple imagelinks, this needs to be exploded to <img src=$images>
</td>
</tr>\n";
}
}
echo "</table>\n";
How can i use the explode function on $images to echo for each imageurl
<img src=$images>
Depending on how those image locations are written in that particular column. If they're separated by ";" then you can use $newarray = explode(";",$afbeeldingen) .. This will give you an array of all the parts separated by ";"... this is just an example..it could be that those image locations are separated by " " or by a "/" .. so you use the character that separates them..then you iterate on the array and you can either divide them on different or in the same but like put them in or

MYSQL SELECT statement with variable based on PHP for loop

Currently, $selection outputs the following: MIN(Bale_ID), MIN(Incoming_Moisture) which is exactly what it should be outputting (they're names from another table). However, when I put $selection into the mysql_query $data1, it seems to just be reading the last value (MIN(Incoming_Moisture)) and only displays the results for that. How do I get the query to read the entire array of elements in $selection? Thank you!!
while ($row1 = mysql_fetch_array($fieldnames1)) {
$fields = $row1['fields1'];
$explode = explode(',',$fields);
if ($row1) {
for ($i=0; $i<$minrows; $i++) {
if ($i<$minrows-1){
$comma = ", ";
}
else {
$comma = "";
}
//$selection = "MIN(".$explode[$i].")".$comma;
//echo $selection;
$data1 = mysql_query("SELECT MIN(".$explode[$i].")".$comma." from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))");
$all1 = mysql_num_fields($data1); //return # of columns; for some reason is returning "1" right now.
while ($row2 = mysql_fetch_array($data1)) {
for ($col=0; $col<$all1; $col++) {
echo $all1;
echo "<td>Min: " . $row2[$col] . "</td>";
}
echo "</tr>";
}
}
}
}
echo "</table>";
Look at the order of operations in your code:
loop {
... fetch data ...
... assign results to $data1 ...
}
Nowhere in your loop do you output or save the results you've got in $data1, so each iteration of the loop overwrites the results of the previous iteration - in other words, only the LAST iteration's results will be stored.
you are running the query once per for loop cycle (1 field at a time) and since first ones yields in SQL error because of the trailin comma, these will not be echoed except the last one.
-- notice the error in first query
SELECT MIN(Bale_ID), from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
SELECT MIN(Incoming_Moisture) from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
use var_dump($selection) instead of echo $selection to see yourself

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