This question already has answers here:
How can I loop through a MySQL result set more than once using the mysql_* functions?
(7 answers)
Closed 7 years ago.
I've been working on a project that prints sql data into a table. Recently, I've come into a problem with the table. What this code should do is output a table of results from a MySQL query but all it's outputting is something like:
Item1 Item1
For some reason it leaves all the other fields blank. Here's my code:
$table = "<table class='TestTable'><tr class='tr'>";
while($row = mysql_fetch_assoc($result)){
$table .= "<th class='th'>";
$table .= $row['NameOfItem'];
$table .= "</th>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "
<td class='td'>Minimum Bid: <b>";
$table .= $row['MinBid'];
$table .= "</b></td>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "<td class='td'>Current Bid: <b>";
$table .= $row['CurrentBid'];
$table .= "</b></td>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "<td class='td'>Sold By: <b>";
$table .= $row['SoldBy'];
$table .= "</b></td>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "<td class='td'>Time Left: <b>";
$table .= printf('%d days, %d hours, %d minutes left', $diff->d, $diff->h, $diff->i);
$table .= "</b></td>";
}
$table .= "</tr></table>";
echo $table;
When I view source I get:
<table class='TestTable'>
<tr class='tr'>
<th class='th'>Item1</th>
<th class='th'>Item1</th>
</tr>
<tr class='tr'></tr>
<tr class='tr'></tr>
<tr class='tr'></tr>
<tr class='tr'></tr>
</table>
After while($row = mysql_fetch_assoc($result)) {...} you have reached the end of your result set. You have to rewind the result pointer to the beginning of the result set if you want to read it again. Do this by using
while($row = mysql_fetch_assoc($result)){ ... }
mysql_data_seek($result, 0); // Rewind result pointer
while($row = mysql_fetch_assoc($result)){ ... }
mysql_data_seek($result, 0); // Rewind result pointer
while($row = mysql_fetch_assoc($result)){ ... }
First get your results and safe them in an array:
while($r = mysql_fetch_assoc($result)){
$row[] = $r;
}
Then reuse the array as often as needed to build the table like this:
$table .= "</tr><tr class='tr'>";
foreach ($row as $r){
$table .= "
<td class='td'>Minimum Bid: <b>";
$table .= $r['MinBid'];
$table .= "</b></td>";
}
... and yes, mysql-functions are deprecated. When you move to PHP7 they'll be gone. Use PDO or mysqli instead.
Related
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>";
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 6 years ago.
(newbie here) I have a php file that is trying to echo out a table displaying movie details and the message below appears everytime:
Notice: Array to string conversion in
/Applications/XAMPP/xamppfiles/htdocs/Unit1/halfTermProjects/associate.php
on line 59
Notice: Array to string conversion in
/Applications/XAMPP/xamppfiles/htdocs/Unit1/halfTermProjects/associate.php
on line 60
A table is echoed below the message that looks like this:
My Code is here (the error occurs when trying to echo the table at the end):
<?php
$filmNames[0]="Hunger Games";
$filmNames[1]="Finding Dory";
$filmNames[2]="Twilight";
$filmNames[3]="Perfect Pitch";
$filmNames[4]="Parent Trap";
$filmNames[5]="Nanny McPhee";
$filmNames[6]="Enchanted";
$filmNames[7]="Frozen";
$filmNames[8]="Bring it On";
$filmNames[9]="Princess Bride";
$filmNames[10]="Mary Poppins";
//Length [0][0] -> [0][10]//
$filmDetails[0][0]=102;
$filmDetails[0][1]=113;
$filmDetails[0][2]=103;
$filmDetails[0][3]=102;
$filmDetails[0][4]=106;
$filmDetails[0][5]=112;
$filmDetails[0][6]=93;
$filmDetails[0][7]=121;
$filmDetails[0][8]=122;
$filmDetails[0][9]=112;
$filmDetails[0][10]=114;
//Rating [1][0] -> [1][10]//
$filmDetails[1][0]=5;
$filmDetails[1][1]=2;
$filmDetails[1][2]=5;
$filmDetails[1][3]=2;
$filmDetails[1][4]=5;
$filmDetails[1][5]=5;
$filmDetails[1][6]=3;
$filmDetails[1][7]=2;
$filmDetails[1][8]=3;
$filmDetails[1][9]=2;
$filmDetails[1][10]=4;
$table = "" ;
$table = "<TABLE border = '1'> ";
$table = $table."<TR>";
$table = $table . "<TH>Film Name</TH>";
$table = $table . "<TH>Film Length</TH>" ;
$table = $table . "<TH>Film Rating</TH>" ;
$table = $table."</TR>";
for ($x = 0; $x<11; $x++){
$table = $table."<TR>";
$table = $table . "<TD>$filmNames[$x]</TD>";
$table = $table . "<TD>$filmDetails([0][$x])</TD>";
$table = $table . "<TD>$filmDetails([1][$x])</TD>";
$table = $table."</TR>";
}
$table = $table . "</TABLE>" ;
echo $table;
echo "<br>";
?>
I changed a little bit of your code.
<?php
$filmNames[0]="Hunger Games";
$filmNames[1]="Finding Dory";
$filmNames[2]="Twilight";
$filmNames[3]="Perfect Pitch";
$filmNames[4]="Parent Trap";
$filmNames[5]="Nanny McPhee";
$filmNames[6]="Enchanted";
$filmNames[7]="Frozen";
$filmNames[8]="Bring it On";
$filmNames[9]="Princess Bride";
$filmNames[10]="Mary Poppins";
//Length [0][0] -> [0][10]//
$filmDetails[0][0]=102;
$filmDetails[0][1]=113;
$filmDetails[0][2]=103;
$filmDetails[0][3]=102;
$filmDetails[0][4]=106;
$filmDetails[0][5]=112;
$filmDetails[0][6]=93;
$filmDetails[0][7]=121;
$filmDetails[0][8]=122;
$filmDetails[0][9]=112;
$filmDetails[0][10]=114;
//Rating [1][0] -> [1][10]//
$filmDetails[1][0]=5;
$filmDetails[1][1]=2;
$filmDetails[1][2]=5;
$filmDetails[1][3]=2;
$filmDetails[1][4]=5;
$filmDetails[1][5]=5;
$filmDetails[1][6]=3;
$filmDetails[1][7]=2;
$filmDetails[1][8]=3;
$filmDetails[1][9]=2;
$filmDetails[1][10]=4;
$table = "" ;
$table = "<TABLE border = '1'> ";
$table = $table."<TR>";
$table .= "<TH>Film Name</TH>";
$table .= "<TH>Film Length</TH>" ;
$table .= "<TH>Film Rating</TH>" ;
$table = $table."</TR>";
for ($x = 0; $x<11; $x++){
$table .= "<TR>";
$table .= "<TD>".$filmNames[$x]."</TD>";
$table .= "<TD>".$filmDetails[0][$x]."</TD>";
$table .= "<TD>".$filmDetails[1][$x]."</TD>";
$table .= "</TR>";
}
$table .= "</TABLE>" ;
echo $table;
echo "<br>";
You cannot just use the variable between " ". It will better for printing it out with "HTML CODE".$variable."HTML CODE" .
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.
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>";
add new product<br>
<br>
<?php
include("mysql.php");
$result = mysql_query("SELECT * FROM gallery ");
$just = mysql_fetch_array($result);
$num=mysql_num_rows($result);
$table="";
$table.="<td>delete</td>";
$table.="<td>update</td>";
if ($num > 0 ) {
$i=0;
while($just = mysql_fetch_array($result))
{
$num=mysql_num_rows($result);
{
$table .= "<tr>";
$table .= "<td>".$just['title']."</td>";
$table .= "<td>".$just['title']."</td>";
}
$table .= "</tr>";
while ($i < $num) {
$name = stripslashes(mysql_result($result,$i,"name"));
$title = stripslashes(mysql_result($result,$i,"title"));
$description = stripslashes(mysql_result($result,$i,"description"));
++$i; }
}
}
else { $table = '<tr><td colspan="2" align="center">Nothing found</td></tr>'; }
?>
<table border="1" cellpadding="1" cellspacing="2"><? echo $table ?></table>
good morning , in the above code iam trying to create a table of 2 columns delete and update , being able to manage mysql through this page , but i get only 1 row from mysql table although i expect 4 (4 rows are saved in mysql table)
what's the wrong here , thanks in advance
add new product<br>
<br>
<?php
include("mysql.php");
$result = mysql_query("SELECT * FROM `gallery`");
$num = mysql_num_rows($result);
$table = "";
$table .= "<td>delete</td>";
$table.="<td>update</td>";
if ($num > 0 ) {
$i=0;
while($just = mysql_fetch_assoc($result)) {
$num=mysql_num_rows($result);
$table .= "<tr>";
$table .= "<td>".$just['title']."</td>";
$table .= "<td>".$just['title']."</td>";
}
$table .= "</tr>";
while ($i < $num) {
$name = stripslashes(mysql_result($result,$i,"name"));
$title = stripslashes(mysql_result($result,$i,"title"));
$description = stripslashes(mysql_result($result,$i,"description"));
++$i;
}
} else {
$table = '<tr><td colspan="2" align="center">Nothing found</td></tr>';
}
?>
<table border="1" cellpadding="1" cellspacing="2"><? echo $table ?></table>
Your fetching the result and counting the rows in the wrong places, and you have a sub while loop that basically does nothing.
Here Try this:
<?php
include("mysql.php");
$result = mysql_query("SELECT `id`,`name`,`title`,`description` FROM gallery");
$table=null;
if (mysql_num_rows($result) > 0 ) {
while($just = mysql_fetch_assoc($result)){
$table .= "<tr>".PHP_EOL;
$table .= "<td>".$just['title']."</td>".PHP_EOL;
$table .= "<td>".$just['title']."</td>".PHP_EOL;
$table .= "</tr>".PHP_EOL;
}
}else{
$table = '<tr><td colspan="2" align="center">Nothing found</td></tr>';
}
?>
<table border="1" cellpadding="1" cellspacing="2"><? echo $table; ?></table>
Good approach but it really require a better implementation.
First, get yourself a function and put it in mysql.php for the frequent use.
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
then write a code to get the data
<?php
include("mysql.php");
$data = sqlArr("SELECT * FROM tbl_names");
foreach ($data as $k => $value) $data[$k] = htmlspecialchars($value);
include 'template.php';
then write a template to make your approach with HTML template complete:
<table border="1" cellpadding="1" cellspacing="2">
<? if (!$data)): ?>
<tr>
<td colspan="2" align="center">Nothing found</td>
</tr>
<? else: ?>
<? foreach($data as $just): ?>
<tr>
<td><?=$just['title']?></td>
</tr>
<? endforeach ?>
<? endif ?>
</table>
Look: your code become 2 times shorter yet WAY more readable!
Note that you shouldn't pass whole data to the editing scripts. Only id is enough and required! Fetch the data to edit from the DB in the update script.
Also note that you shouldn't use GET method to delete records - only post. So, let me suggest you to have a "Delete" button not in the table but in the update form.