php PDO read to table statement - php

here is the code
$sql = "SELECT * FROM $table ";
foreach ($db->query($sql) as $row) {
echo "<tr>"."\n";
echo '<td>'. $row[CODE].'</td>';
echo '<td>'. $row[FIRME_CODE].'</td>';
echo '<td>'. $row[NOM_LEGAL].'</td>';
echo '<td>'. $row[NO_CIVIQUE].'</td>';
echo '<td>'. $row[NOM_RUE].'</td>';
.... and so on ...
echo "</tr>"."\n\n";
}
the question, how it's possible to output all the value found from the query into a table WITHOUT having to tell each array table value individually...
it does not make sens... so there must be a way to do it, fast...
--
after changing it to this.. it output the word : Array in each table cell
<td> Array </td>... not good !
So the question is... what is the error in this code ?
$sql = "SELECT * FROM $table ";
$rows = $db->query($sql);
echo '<tr>';
foreach ($rows as $key => $value) {
echo '<td>', $key, '</td>';
}
echo '</tr>';

echo '<tr>';
foreach ($row as $key => $value) {
echo '<td>', htmlspecialchars($value), '</td>';
}
echo '</tr>';
Note that I've added htmlspecialchars() which will escape your arbitrary data for use in HTML, generating valid HTML and preventing against potential XSS attacks (depending on where that data comes from).

put the query result in an array
and then foreach the array
$sql = "SELECT * FROM $table ";
$rows = $db->query($sql);
foreach ($rows as $row) {
echo '<td>'.implode('</td><td>',$row).'</td>';
}

Related

Pulling data from database and into an html table

I'm pulling data from a database but only getting the first row into the dynamically produced html table.
I've tried adding another foreach loop but that isn't the answer… I'm out of ideas...
$conn = new PDO('mysql:host=localhost;dbname=jeuxvideo', $dbUserName, $dbPassword);
$sql = "SELECT * FROM jeuxvideo";
$result = $conn->prepare($sql);
$request = $result->execute();
echo "<table border='1'>";
echo "<tr><td>Id</td><td>Titre</td><td>Prix<td>Date de Sortie</td><td>Genre</td><td>Origine</td><td>Mode</td><td>Connexion</td></tr>\n";
$row = $result->fetch(PDO::FETCH_ASSOC);
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
echo "</table>";
This code pulls all the correct info and puts it in the right place in the html table, but for some Reason it doesn't collect the Following rows data...
This line only fetches one row:
$row = $result->fetch(PDO::FETCH_ASSOC);
You need to fetch as many rows it can give you. Once there are no more rows to fetch the function will return FALSE, so you can use with the while loop, like this:
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
echo "</table>";
Since you don't have any variables you need prepared for your query, you can simply do:
<?php
$stmt = $pdo->query('SELECT * FROM jeuxvideo');
echo '<table>';
foreach ($stmt as $row) {
echo '<tr>';
echo "<td>$row['name']</td>";
echo "<td>$row['url']</td>";
echo "<td>$row['timestamp']</td>";
echo '</tr>';
}
echo '</table>';
A 2nd method would be:
<?php
$stmt = $pdo->query('SELECT * FROM jeuxvideo');
echo '<table>';
while ($row = $stmt->fetch()) {
echo '<tr>';
echo "<td>$row['name']</td>";
echo "<td>$row['url']</td>";
echo "<td>$row['timestamp']</td>";
echo '</tr>';
}
echo '</table>';
Try this
$conn = new PDO('mysql:host=localhost;dbname=jeuxvideo', $dbUserName, $dbPassword);
$sql = "SELECT * FROM jeuxvideo";
$result = $conn->prepare($sql);
$request = $result->execute();
echo "<table border='1'>";
echo "<tr><td>Id</td><td>Titre</td><td>Prix<td>Date de Sortie</td><td>Genre</td><td>Origine</td><td>Mode</td><td>Connexion</td></tr>\n";
$row = $request->fetch_all();
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
echo "</table>";

Show table's data

I use this code to show data from a selected table by the user
$query = 'SELECT * FROM '.$Nom_table;
$query = $dbh -> query($query);
$result = $query -> fetchAll(PDO::FETCH_ASSOC);
echo '<table>';
while(list ($key, $array) = each($result))
{
foreach($array as $table)
{
echo $table.'';
}
}
echo '</table>';
by I don't know the name of the columns to show data so what's the solution to show all data from any tables ?
All you have to do is basically do something like this:
while($result = $query->fetch(PDO::FETCH_ASSOC))
{
foreach($result as $column => $value)
{
echo "<tr>";
echo $table . "<td>" . $column . "</td><td>" . $value . "</td>";
echo "</tr>"
}
}
This should work for any table in your database. Then it's just a matter of formatting your HTML to look like what you want.
use SHOW COLUMNS like this:
SHOW COLUMNS FROM your_table_name;
use print_r() to print your array result, see all the columns and then do whatever you want to do...
while(list ($key, $array) = each($result))
{
echo "<pre>";
print_r($array);
}

looping through table rows php CSS

I am looping through an array of results that I have gathered from the database. There are no problems in regards to displaying the data gained from the database. The problem sits within the styling of the data.
I have some CSS for the code below, it styles the first row of data but the rest are just echoed with no styling although they do look as if they sit within the table that is being defined within the php.
$user = $_SESSION['sess_uid'];
$conn = new mysqli(localhost, root, DBPASS, DBNAME);
$sql = "SELECT * FROM reports WHERE userID = '" . $conn->real_escape_string($user)."';";
// Performs the $sql query on the server
$result=mysqli_query($conn,$sql);
$rows[] = array();
echo '<table>';
echo '<thead>';
echo '<tr>';
echo '<th> Report Name </th>';
echo '<th> Category Name </th>';
echo '<th> Sub Category Name </th>';
echo '<th> Date Uploaded </th>';
echo '</tr>';
echo '</thead>';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tbody>';
$rows[] = $row;
echo '<tr>';
echo '<td>'.$row['reportName'].'</td>'.'<td>'.$row['categoryName'].'</td>'.'<td>'.$row['subcategoryName'].'</td>'.'<td>'.$row['reportDateUploaded'].'</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
};
Any thoughts?
Thanks
You need to make your while statement only contain your tr and td elements.
You need to put the tbody and table tags out of your while loop.
echo '<tbody>';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
echo '<tr>';
echo '<td>'.$row['reportName'].'</td>'.'<td>'.$row['categoryName'].'</td>'.'<td>'.$row['subcategoryName'].'</td>'.'<td>'.$row['reportDateUploaded'].'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';

Get field names from database result

Here I want to fetch the field names from the table name which is stored in the variable $table. And want to make a table headers of the field names. What's wrong with this approach I tried:
<?php
$sql=mysql_query("show fields from $table");
if(mysql_num_rows($sql))
while($res = mysql_fetch_object($sql))
{
?>
<th><?php echo $res->field; ?></th>
<?
}
else
{
echo "No data to display";
}
?>
$printTHs = true;
while($res = mysql_fetch_assoc($sql))
{
if ($printTHs)
{
printTableHeader($res);
$printTHs= false;
}
echo "<tr>";
foreach($res as $val)
{
echo "<td>" . $val . "</td>";
}
echo "</tr>";
}
function printTableHeader($res)
{
echo "<tr>";
foreach($res as $col => $val)
{
echo "<th>" . $col . "</th>";
}
echo "</tr>";
}
The query has to be
$sql=mysql_query("show columns from $table");
Use mysql_fetch_assoc() and then get the keys using array_keys(). This will return an array with all the keys.
Use foreach() to get your table headers
Not the optimal solution, but would do it:
$results = mysql_query('SELECT * FROM ' . $table);
if (mysql_num_rows($results))
{
echo '<table>';
$first = TRUE;
while ($row = mysql_fetch_assoc($results))
{
if ($first = TRUE)
{
echo '<tr>';
foreach ($row as $k => $v)
echo '<th>' . $k . '</th>';
echo '</tr>';
$first = FALSE;
}
echo '<tr>';
foreach ($row as $column)
echo '<td>' . $column . '</td>';
echo '</tr>';
}
echo '</table>';
}

How to echo out table rows from the db (php)

i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but what I want is all of them, echoed out one after the other. How can I turn a mysql result into something I can use?
I tried:
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
$res = mysql_result($results, 0);
while ($res->fetchInto($row)) {
echo "<form id=\"$row[0]\" name=\"$row[0]\" method=post action=\"\"><td style=\"border-bottom:1px solid black\">$row[0]</td><td style=\"border-bottom:1px solid black\"><input type=hidden name=\"remove\" value=\"$row[0]\"><input type=submit value=Remove></td><tr></form>\n";
}
$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
echo "<tr>";
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.
Wrapped in <table> so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
echo "<tr>";
foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.
Nested loop to display all rows & columns of resulting table:
$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
for( $j = 0; $j<$cols; $j++ ) {
echo mysql_result($result, $i, $j)."<br>";
}
}
Can be made more complex with data decryption/decoding, error checking & html formatting before display.
Tested in MS Edge & G Chrome, PHP 5.6
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach() (because it is "iterable") which eliminates the need to maked iterated _fetch() calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id'])

Categories