Iterating through column values for multiple rows mysqli - php

I have a table with 4 values, 3 of which I am interested in. The MYSQL query I am using is:
Select Product.product_id, Product.cost, Product.image from Product
I have tested this query and it works with my database. I can figure out how to get single columns to return values, but I cannot figure out multiple columns. I have tried a variety of for loops, using an array to store the various column names and iterating things. I'm getting very frustrated, and am not sure what to do.
This was my last attempt:
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database');
$stmt = "Select Product.product_id, Product.cost, Product.image from Product";
if(!$result = $conn->query($stmt)){
die('there was an error retrieving the information');
}
$tablebuild = "<table>";
while ( $row = $result->fetch_assoc() ){
foreach ($row as $next){
$tablebuild .= "<tr><td>";
$tablebuild .= $result['product_id'];
$tablebuild .= "</td><td>";
$tablebuild .= $result['cost'];
$tablebuild .= "</td><td>";
$tablebuild .= $result['image'];
$tablebuild .= "</td></tr>";
}
$tablebuild .= "</table>";
Obviously I'm trying to build it into a string of code so I can echo it later into the page where I need it. Every time I run this page, though, I get nothing but a blank page with no source code.

Lose the foreach and use $row, not $result
while ( $row = $result->fetch_assoc() ){
$tablebuild .= "<tr><td>";
$tablebuild .= $row['product_id'];
$tablebuild .= "</td><td>";
$tablebuild .= $row['cost'];
$tablebuild .= "</td><td>";
$tablebuild .= $row['image'];
$tablebuild .= "</td></tr>";
}

I think your problem is that you dont close your while loop ,also your foreach is not correct ,this is how it should be even if it's not necessary :
$tablebuild .= "<table>";
while ( $row = $result->fetch_assoc() ){
$tablebuild .= "<tr>";
foreach ($row as $next){
$tablebuild .= "<td>$next<td>";
}
$tablebuild .= "</tr>";
}
$tablebuild .= "</table>";

Related

Why does only one row display correctly when dumping MYSQL table?

I'm trying to dump my MYSQL table via PHP onto my HTML page and I'm having some issues that I've hit a bump on.
Currently I have (Using Bootstrap 4):
require('db.php');
$sql = "SELECT * FROM `users`;";
$table = "";
$result = mysqli_query($connection, $sql) or die(mysql_error());
$table = "<table class='table table-hover table-dark'>";
$table .= "<thread>";
$table .= "<tr>";
$fieldsInfo = $result->fetch_fields();
foreach($fieldsInfo as $fieldinfo)
$table .= "<th scope='col'>{$fieldinfo->name}</th>";
$table .= "</tr>";
$table .= "</thead>";
$table .= "<tbody>";
while ($row = $result->fetch_assoc()) {
$table .= "<tr>";
foreach ($row as $columnValue) {
$table .= "<td>$columnValue</td>";
}
$table .= "</tr>";
$table .= "</tbody>";
$table .= "</table>";
}
echo $table;
?>
And my result looks like so:
Table Display
I believe it's where I'm placing the <tr> and </tr> values in my code, but I've tried placing them both inside and out side of my loops. When placed inside of my loop my table returns all my column values into the first table heading. I further inspected my code via Firefox 'inspect element' and I saw that the second row from the table is actually outside the scope of <table> which makes no sense to me because my loop is obviously before I use </table>.
Hopefully someone can shed some light on this for me, I'm just starting to use PHP so I'm not great with it; but I want to learn.
Your <tr> and </tr> tags look fine where they are. The problem is that the closing </tbody> and </table> tags are inside the while loop. Move them down and it should come out right.
while ($row = $result->fetch_assoc()) {
$table .= "<tr>";
foreach ($row as $columnValue) {
$table .= "<td>$columnValue</td>";
}
$table .= "</tr>";
}
$table .= "</tbody>";
$table .= "</table>";
echo $table;
Use this code :
while ($row = $result->fetch_assoc()) {
$table .= "<tr>";
foreach ($row as $columnValue) {
$table .= "<td>$columnValue</td>";
}
$table .= "</tr>";
}
$table .= "</tbody>";
$table .= "</table>";

How to remove selected columns from dynamically generated html-table?

I have an SQL-database where I read out data that are then shown in a dynamically generated html-table. Here is my code that works fine:
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray";
$result = mysqli_query($db, $sql) or die("Invalid query");
$numrows = mysqli_num_rows($result);
$numcols = mysqli_num_fields($result);
$field = mysqli_fetch_fields($result);
if ($numrows > 0) {
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) {
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
}
mysqli_close($db);
Now, I want to remove specific columns (e.g. those, which are empty or those, which are not that interesting for the user, who makes the request).
I tried it with unset($field[$variable]), however, it didn't work. In addition, the values (if there are any), should be removed, too.
can let mysql filter them out for you,
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray AND LENGTH($selection) > 0";
-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length
Always format the array before you print it. Try to remove the specific columns from the $field array before you echo the HTML and then print the final table. Once the HTML code is echoed in PHP you won't be able to remove it without the use of JavaScript.
You can check against the $field[$x]->name variable and use continue to skip the column.
<?php
// DataBase Config - http://php.net/manual/pt_BR/pdo.construct.php.
$dsn = 'mysql:host=localhost;dbname=test';
$usr = 'root';
$pwd = '';
try { // try to connect in database.
$pdo = new PDO($dsn, $usr, $pwd);
} catch (PDOException $e) { // if there is error in the connection.
die('Connection failed: ' . $e->getMessage());
}
// Prepare Statement and execute - http://php.net/manual/pt_BR/pdo.prepare.php.
$stm = $pdo->prepare('select id, weight, color, name from product');
$stm->execute();
// Get ALL rows - Object.
$rows = $stm->fetchAll(PDO::FETCH_OBJ);
// Print Rows.
//echo '<pre>'.print_r(rows, true).'</pre>';
// Check $row;
if (count($rows)) {
// Order and Display Cols.
$colsDisplay = [
'id' => 'ID Product',
'name' => 'Name',
'weight' => 'Weigth'
];
// Table.
$html = '<table border="1">';
$html .= "\n <thead>";
$html .= "\n <tr>";
$html .= "\n <th bgcolor='#eee'>Row</th>";
$html .= "\n <th>". implode("</th>\n <th>", $colsDisplay) ."</th>";
$html .= "\n </tr>";
$html .= "\n </thead>";
$html .= "\n <tbody>";
// Loop ROWS.
foreach ($rows as $key => $val) {
$html .= "\n <tr>";
$html .= "\n <td bgcolor='#eee'>". $key ."</td>";
// Loop COLS to display.
foreach ($colsDisplay as $thKey => $thVal) {
$html .= "\n <td>". $val->$thKey ."</td>";
}
$html .= "\n </tr>";
}
$html .= "\n".' </tbody>';
$html .= "\n".'</table>';
echo $html;
}
In order to know that a column is empty, you should check the whole column. There are different ways to do it, one of them could be investigating which of them are empty and then only using those that aren't empty. Something like this:
<?php
// ...
$q = "SELECT SUM(LENGTH(my_first_column)) col_0, SUM(LENGTH(my_second_column)) col_1, ..., SUM(LENGTH(my_11th_column)) col_10 FROM $tabelle WHERE $masterarray";
// ... execute query and return results in $nonEmpty
$nonEmpty = array();
foreach($row as $columnIndex) {
if ($row[$columnIndex] > 0) {
$nonEmpty[] = $columnIndex;
}
}
// ... now go through results and print only cols with at least one row with lenght > 0 i.e. non empty
$len = 11;
$rowHTML = "<tr>";
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < $len; ++$i) {
$rowHTML = '';
if (!in_array($i, $nonEmpty)) {
$rowHTML .= '<td>' . $row[$i] . '</td>';
}
$rowHTML .= "</tr>\n";
}
}
// ...
This chunk of code will remove columns with ALL empty values. If you have at least one cell in the column with some value, you'll see the column in your result.
The code isn't optimized - it's just a rough idea. But it's a starting point.

Looping of tables when search button is press

I have problems with looping of my table when displaying here are the codes
<html>
<?php
$Candidate =$_POST ['candidate'];
$link = mysqli_connect('localhost', 'root', '', 'test') or die(mysqli_connect_error());
$query = "SELECT * FROM `table 1` WHERE `fullname` LIKE '$Candidate%'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
mysqli_close($link);
$row=mysqli_fetch_assoc($result);
while ($row = mysqli_fetch_array($result))
{
echo <table>
echo "Name Of Candidate:". #$row['fullname'];
echo "<br>";
echo "comments:".#$row['comments'];
}
?>
initially i want the search results to be displayed in a table format any help?
You can try following
echo "<table>";
while ($row = mysqli_fetch_array($result))
{
echo "<TR><TD>Name Of Candidate:" . $row['fullname'] . "</td>";
echo "<TD>comments:" . $row['comments'] . "</TD></TR>";
}
echo "</table>";
First of all your code is vulnerable to MySQL injection attack. See this SO post
Talking about rendering of the table, the following code should do just fine:
$table = "<table>\n";
$tableHead = <<<THEAD
<thead>\n
<tr>\n
<th>Name of candidate</th>\n
<th>Comments</th>\n
</tr>\n
</thead>\n
THEAD;
//Add table head
$table .= $tableHead;
while ($row = mysqli_fetch_array($result)) {
//No need for # before $row, since your table will have those columns?
$tableRow = <<<TABLEROW
<tr>\n
<td>{$row['fullname']}</td>\n
<td>{$row['comments']}</td>\n
</tr>\n
TABLEROW;
$table .= $tableRow;
}
//Close the table
$table .= "</table>\n";
//Print the table
echo $table;

Search multiple tables and display as multiple tables

I want my users to search my database to return data from two different tables which I have done using UNION but I want it to not only search from two tables but to also display as two tables..How can I go about doing this?
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Part</td><td>Gids</td></tr>";
while ($row = mysql_fetch_array($sql)){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Part'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Dish</td><td>Gids</td></tr>";
while ($row = mysql_fetch_array($sql)){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Dish'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";
If you're going to do it this way, you need some way to tell where the first results end and the second start. An easy way is to add an extra column in the result set:
Select
0 as resultset,
Name,
Part,
Gid
From
Parts
Union All
1,
Name,
Dish,
Gid
From
Dishes
Order By
resultset -- I'm not sure if you need this, or whether you get it for free
Then you need to break out of the first loop if you've moved to the second result set. Also, the column names in the union will all reflect the first part, so I've changed Dish to Part. You also have to deal with the possibility that either or both of the parts of the union may return nothing.
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Part</td><td>Gids</td></tr>";
while ($row = mysql_fetch_assoc($sql) && $row['resultset'] === 0) {
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Part'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Dish</td><td>Gids</td></tr>";
while ($row){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Part'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
$row = mysql_fetch_assoc($sql);
}
$result .= "</table>";
Your probably do have two tables but right next to each other. Try putting something visble in between. I put an HR but you can put what makes sense visually for your page. Even a BR ot table header text would work.
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Part</td><td>Gids</td></tr>";
while ($row = mysql_fetch_array($sql)){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Part'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";
$result .= "<hr />"; <=========
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Dish</td><td>Gids</td></tr>";
while ($row = mysql_fetch_array($sql)){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Dish'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";

Dynamically generate html table with php of mysql records

The reason this is complicated (for me) is that each column of the table is loaded from a separate MySQL table, and each MySQL table will have varying number of records. Initially I thought I could start generating the html table from top-left to bottom-right column by column , cell by cell, but this won't work because each MySQL table will have different length of records, which generate malformed html tables. Do you have any suggestions?
My idea so far:
Get a list of all tables in MySQL, which determine the number of
columns
Get the count from the table with most records
Create a table with the parameters (# of tables as columns, max# as rows
Update each cell with the corresponding record, but not quite sure how
As requested, some code:
$tables = mysql_query("show tables");
$output = "<table border=1><thead><tr>";
while($table = mysql_fetch_array($tables)) {
$output .= "<td>";
$output .= $table[0];
$output .= "</td>";
$tableNames[] = $table[0];
}
$output .= "</tr></thead>";
$output .= "<tbody>";
//Get a count of the table with the most records
for($i=0; $i<count($tableNames); $i++ ){
$currentTable = $tableNames[$i];
$tableContent = mysql_query("select * from $currentTable") or die("Error: ".mysql_error());
//Generating all content for a column
$output .= "<tr>";
while($content = mysql_fetch_array($tableContent)){
//generating a cell in the column
$output .= "<td>";
$output .= "<strong>".$content['subtheme'].": </strong>";
$output .= $content['content'];
$output .= "</td>";
}
$output .= "</tr>";
}
$output .= "</tbody>";
$output .= "</table>";
This is wrong not just because it generates a malformed table, but also because it transposed columns to rows...
Any help would be appreciated
Solution to my much hated question:
$mymax = 0;
for($i=0; $i<count($tableNames); $i++){
$currentTable = $tableNames[$i];
$tableCounts = "select * from $currentTable";
if($stmt = $mysqli->prepare($tableCounts)){
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt);
mysqli_stmt_close($stmt);
}
($mymax >= $count ? "" : $mymax = $count);
$colWidth = 100 / count($tableNames);
}
// DIV GRID
// via DIV GENERATION
$output .= "<div class='grid'>";
for ($i=0; $i<count($tableNames); $i++){
$output .= "<div id='col$i' class='col' style=\"width:$colWidth%\">";
$output .= "<h3>".$tableNames[$i]."</h3>";
$tableqry = "select * from $tableNames[$i]";
if ($result = mysqli_query($mysqli, $tableqry)) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$output .= "<div class='item'>".$row["content"]."</div>";
}
mysqli_free_result($result);
}
$output .= "</div>";
}
$output .="</div>";
$output .="<div class='clear'></div>";

Categories