foreach warning in PHP - php

admin TABLE
+--------------+---------------+
| Username | Password |
+--------------+---------------+
| JOHN | 123 |
| EDWARD | 123 |
+--------------+---------------+
my code
$result = mysqli_query($connection, $query);
echo" <table >";
$row = mysqli_fetch_assoc($result);
echo "<tr>";
foreach($row as $key => $val){
echo"<th>$key</th> ";
echo "</tr>";
///////////////////////////////
$result = mysqli_query($connection, $query);
echo"<tr>";
while($row = mysqli_fetch_assoc($result)){
foreach($row as $key => $val){
echo "<td>$val</td>";
}
echo "</tr>";
}
echo "</table>";
}
So, the problem is if there is more than 1 row in the result it outputs exactly what i want for e.g if i say:
SELECT Username from admin;
+--------------+
| Username |
+--------------+
| JOHN |
| EDWARD |
+--------------+
But if there is only one row it does not show the COLUMN name and gives this warning
Select Username from admin where Username = 'JOHN';
Warning: Invalid argument supplied for foreach() on line 65
+--------------+
| JOHN |
+--------------+

Sneaky typo/logical coding error: you have a curly-bracket (brace) that's screwing everything up. Look at the end of the foreach used to generate the headings:
foreach($row as $key => $val){
echo"<th>$key</th> ";
This should be:
foreach($row as $key => $val)
echo"<th>$key</th> ";
And then remove the spurious brace at the very end.
This works (so long as there is at least 1 row to get the heaedrs):
$result = mysqli_query($connection, $query);
echo " <table >";
$row = mysqli_fetch_assoc($result);
echo "<tr>";
foreach($row as $key => $val)
echo"<th>$key</th> ";
echo "</tr>";
$result = mysqli_query($connection, $query);
echo"<tr>";
while($row = mysqli_fetch_assoc($result))
{
foreach($row as $key => $val)
{
echo "<td>$val</td>";
}
echo "</tr>";
}
echo "</table>";

Related

How to display the comment only once but display all images from mysql in PHP?

I want to display the comment only once e.g (testsetest) with the related images (which has the same imagesid by connecting the two tables).
Example (that I want to achieve):
comment: fool with images: name1, name 2
Caption of the wrong output.
The database structure
posts:
| commentid | comment | iamgesid |
------------------------------------
| 1 | fool | 5557 |
| 2 | fool2 | 5585 |
------------------------------------
multiple_image:
| id | image | imagesid |
---------------------------
| 1 | name1 | 5557 |
| 2 | name2 | 5557 |
| 3 | name3 | 5585 |
---------------------------
This is my current code:
$sql = "SELECT image, posts.imagesid, multiple_image.imagesid, comment
FROM multiple_image JOIN posts ON (multiple_image.imagesid=posts.imagesid)";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['comment'];
$imgs= "<div id='img_div'><img width='' src='upload/".$row['image']."' ></div>";
echo $imgs;
}
}
You will need to control break the result and order by the commentid
Please see the updated code.
$sql = "SELECT
image,
posts.imagesid,
multiple_image.imagesid,
comment
FROM
multiple_image
JOIN posts ON (multiple_image.imagesid=posts.imagesid)
ORDER BY
commentid
";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
if ($result->num_rows > 0) {
// output data of each row
$comment = '';
while($row = $result->fetch_assoc()) {
if($comment != $row['comment']){
echo $row['comment'];
$comment = $row['comment'];
}
$imgs= "<div id='img_div'><img width='' src='upload/".$row['image']."' ></div>";
echo $imgs;
}
}
You can create a flag and check if it is 0. If it is 0 then you can show comment else you dont need to show comment. Check below code:
if ($result->num_rows > 0) {
// output data of each row
$loop = 0;
while ($row = $result->fetch_assoc()) {
if ($loop == 0) {
echo $row['comment'];
}
$imgs = "<div id='img_div'><img width='' src='upload/" . $row['image'] . "' ></div>";
echo $imgs;
$loop++;
}
}
Hope it helps you.
I hope it will help out:
$sql = "SELECT
image,
posts.imagesid,
multiple_image.imagesid,
comment
FROM
multiple_image
JOIN posts ON (multiple_image.imagesid=posts.imagesid)
ORDER BY
commentid";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
if ($result->num_rows > 0) {
$comment = array();
while ($row = $result->fetch_assoc()) {
// check imagesid is not exist in array
if (in_array($row['imagesid'], $comment) == false) {
echo $row['comment'];
$comment[] = $row['imagesid'];
}
$imgs = "<div id='img_div'><img width='' src='upload/" . $row['image'] . "' ></div>";
echo $imgs;
}
}

Creating a dynamic table with rowspan PHP

How to create a table with data retrieved from MySQL with PHP
-------------------------
| albumID | trackID |
-------------------------
| | 1990 |
- 1 -------------
| | 1991 |
-------------------------
| | 1992 |
- -------------
| 2 | 1993 |
- -------------
| | 1994 |
-------------------------
I can generate a table from the database, but the result will be only like each result in one row
$query = "SELECT albumID, trackID
FROM songs";
$result = mysqli_query($db, $query);
echo "<table>";
echo "<tr>\n";
echo "<th>albumID</th>\n";
echo "<th>trackID</th>\n";
echo "</tr>\n";
while ($data = mysqli_fetch_array($result)) {
echo "<tr>\n";
echo "<td>$data[0]</td>\n";
echo "<td>$data[1]</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
Any help given is really appreciated!
You can do this by using a variable to keep track of the current album and only output the album once as shown below.
$current_album = ''; # initialize tracking var
while ($data = mysqli_fetch_array($result)) {
echo "<tr>\n";
if ($current_album != $data[0]) {
echo "<td>$data[0]</td>\n";
$current_album = $data[0];
} else {
echo "<td> </td>\n"; # insert empty cell
}
echo "<td>$data[1]</td>\n";
echo "</tr>\n";
}
This will have the album ID appearing in the first row for the album. If you want it to be vertically centered you can use rowspan on the td element, but in order to know how many rows each album has you will either need to update your sql query to return that or you can process the results into a multidimensional array and then loop through that to generate the output.
Maybe not the most elegant solution, but should do the trick.
$query = "select albumID as album, group_concat(trackID) as tracks from songs group by albumID";
$result = mysqli_query($db, $query);
echo "<table>";
echo "<tr>\n";
echo "<th>albumID</th>\n";
echo "<th>trackID</th>\n";
echo "</tr>\n";
while ($data = mysqli_fetch_array($result)) {
$tracks = explode(",", $data[1]);
echo "<tr>\n";
echo "<td rowspan=\"".count($tracks)."\">$data[0]</td>\n";
foreach ($tracks as $key => $value) {
echo "<td>$value</td>\n"
}
echo "</tr>\n";
}
echo "</table>\n";
Edit your query to return the numbers of tracks of the album and use that number to create a rowspan only on the first track row. I wrote a little example but I havn't tried if it works.
$query = "SELECT s.albumID, s.trackID,
( SELECT COUNT(*)
FROM songs s2
WHERE s2.albumID = s.albumID )
FROM songs s";
$result = mysqli_query($db, $query);
echo "<table>";
echo "<tr>\n";
echo "<th>albumID</th>\n";
echo "<th>trackID</th>\n";
echo "</tr>\n";
$tmpAlbum = '';
while ($data = mysqli_fetch_array($result)) {
echo "<tr>\n";
echo "<td";
if($data[2] == 1){
echo "<td>$data[0]</td>\n";
}else{
if($data[0] != $tmpAlbum){
echo "<td rowspan=\"".$data[2]."\">$data[0]</td>\n";
}
}
$tmpAlbum = $data[0];
echo "<td>$data[1]</td>\n";
echo "</tr>\n";
}
echo "</table>\n";

How to Echo Datas From Mysql Properly

I have a mini game which is written in PHP. I want to build a highscore section for it. But I can't echo datas properly. My database
+--------+----------+----------------------------------+---------------------+------+------+
| UserID | Username | Password | EmailAddress | win | lost |
+--------+----------+----------------------------------+---------------------+------+------+
| 1 | utku | e10adc3949ba59abbe56e057f20f883e | utku#utku.com | 3 | 6 |
| 2 | utku2 | e10adc3949ba59abbe56e057f20f883e | utku#sda.com | 5 | 15 |
| 3 | utku3 | e10adc3949ba59abbe56e057f20f883e | sad | 0 | 0 |
+--------+----------+----------------------------------+---------------------+------+------+
I'm trying to echo them with this code (I found it in another question's topic)
<?php include "base.php"; ?>
<?
$query="SELECT Username,win,lost FROM users ORDER BY win";
$results = mysql_query($query);
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr><br>';
}
?>
It prints datas like this
utku3utku30000
utkuutku3366
utku2utku2551515
But I want to print them in this form
Username Win Lost
utku2 5 15
utku 3 6
utku3 0 0
How can I do it. I'm new on PHP
You should not use mysql_ as it is outdated and will be removed in future versions of php.
You should switch to mysqli_ or PDO. (Overview of the MySQL PHP drivers > Choosing an API)
Your problem is:
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
MYSQL_BOTH: [...]By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.[...]
That's why you get each column twice.
A quick fix would be using MYSQL_NUM or MYSQL_ASSOC:
mysql_fetch_array($results, MYSQL_ASSOC)
You should not print tr, td without table tag. Also you did not added th. Can try this
echo '<table><tr><th>User Name</th><th>Win</th><th>Lost</th></tr>';
while ($row = mysql_fetch_array($results)) {
echo '<tr><td>'.$row['Username'].'</td><td>'.$row['win'].'</td><td>'.$row['lost'].'</td></tr>';
}
echo '</table>';
You don't need the foreach loop because the while loop is doing the recursive iteraction, that's why you have twice results:
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
echo '<td>' . htmlspecialchars($field['Username']) . '</td>';
echo '<td>' . htmlspecialchars($field['win']) . '</td>';
echo '<td>' . htmlspecialchars($field['lost']) . '</td>';
echo '</tr><br>';
}

MYSQL PHP Output sorting, get values inbetween output

I have a small problem with MySQL tables pushed into a HTML table.
Here is my SELECT on the database:
$result = mysql_query("
SELECT dat_eb_registrants.id, dat_eb_registrants.first_name, dat_eb_registrants.last_name, dat_eb_registrants.email, dat_eb_registrants.comment, dat_eb_registrants.amount, dat_eb_registrants.published, dat_eb_registrants.transaction_id, dat_eb_registrants.register_date, GROUP_CONCAT(dat_eb_field_values.field_value SEPARATOR '</td><td>')
FROM dat_eb_registrants LEFT JOIN dat_eb_field_values ON dat_eb_registrants.id=dat_eb_field_values.registrant_id
WHERE `event_id` >= 20 AND `event_id` <= 25
GROUP BY dat_eb_registrants.id
ORDER BY $sort $ascdsc
");
Which is pushed into my HTML table using this:
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[9] . "</td>";
echo "<td>";
Now, my problem is the fact that this fills my table with a few rows from dat_eb_field_values.field_value, and I can't get other rows ($row[0] to $row[8]) in-between these results.
For example if my $values come from dat_eb_field_values.field_value and my $data comes from dat_eb_registants. This would be my table:
| header 1 | header 2 | header 3 | header 4 | header 5 | header 6 |
-------------------------------------------------------------------
| $value1 | $value2 | $data3 | $value4 | $data1 | $data2 |
| $value1 | $value2 | $data3 | $value4 | $data1 | $data2 |
| $value1 | $value2 | $data3 | $value4 | $data1 | $data2 |
Thanks in advance! Laurent
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
foreach($row AS $val)
echo "<td>" . $val . "</td>";
echo "<td>";
}
that should do
Instead of echoing out the data of $row[9] place it in a array, then spit it out when you feel it's necessary (and after you've checked for the other elements)
For example change this:
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[9] . "</td>";
echo "<td>";
To this:
while ($row = mysql_fetch_row($result)) {
$myArray[] ="<tr><td>" . $row[9] . "</td>""<td>";
instead of mysql_fetch_row use mysql_fetch_array
and
ORDER BY $sort $ascdsc change it to
ORDER BY '".$sort."', '".$ascdsc."'
exemple :
by using mysql_fetch_array try echo this
echo $row['dat_eb_registrants.id'] ;
your sql is hard to read
use this
SELECT dr.id, dr.first_name, dr.last_name, dr.email, dr.comment, dr.amount, dr.published, dr.transaction_id, dr.register_date, GROUP_CONCAT(df.field_value SEPARATOR '</td><td>')
FROM dat_eb_registrants dr
LEFT JOIN dat_eb_field_values df
ON dr.id=df.registrant_id
WHERE `event_id` >= 20 AND `event_id` <= 25
GROUP BY dr.id
ORDER BY '".$sort."', '".$ascdsc."'
but you have accepted the answer here !!

Query result records to column for comparison

Is there anyway to achieve displaying query results into columns and have the records go to the next row?
Here's my SQL table:
------------SQL TABLE -----------
id | product_name | product_type
0 | Lorem | Table
1 | Ipsum | Chair
2 | Dolor | Lamp
3 | Sit | Chair
This is what I would like.
Lorem | Ipsum | Dolor | Sit |
------------------------------------------------------------
id | 0 | 1 | 2 | 3 |
type | Table | Chair | Lamp | Chair |
Desired output:
<table>
<tr>
<td> </td>
<td>Lorem</td>
<td>Ipsum</td>
<td>Dolor</td>
<td>Sit</td>
</tr>
<tr>
<td>id</td>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>type</td>
<td>Table</td>
<td>Chair</td>
<td>Lamp</td>
<td>Chair</td>
</tr>
</table>
This is my code, but I know this is terribly wrong. I'm just stuck on how to make a new row for a field if that makes sense using while and for loops.
echo '<table><tr>';
$i=1;
while($rows = mysql_fetch_array($result)){
echo '<td><table><tr><th>'.$rows['product_name'].
'</th></tr><tr><td>'.$rows['product_id'].
'</td><td>'.$rows['product_type'].'</tr></table></td>';
if($i %2 == 0) {
echo '</tr>
<tr>'; }
}
echo'
</tr>
</table>';
You need to rotate your data.
You could use something like this (untested):
// build query
$query = "SELECT id, product_name, product_type FROM whatevertableyouhave";
// query the database
$result = mysql_query($query);
// cols we are interested in (from the SQL query)
$cols = array(
'id',
'product_name',
'product_type';
);
// initialize rotated result using cols
$rotated = array();
foreach($cols as $col) {
$rotated[$col] = array();
}
// fill rotated array
while(($row = mysql_fetch_assoc($result)) !== false) {
foreach($cols as $col) {
$rotated[$col][] = $row[$col];
}
}
// echo html
echo "<table>";
echo "<tr>";
foreach($cols as $col) {
echo "<th>{$col}</th>";
}
echo "</tr>";
foreach($rotated as $col => $values) {
echo "<tr>";
foreach($values as $value) {
echo "<td>" . htmlentities($value) . "</td>";
}
echo "</tr>";
}
echo "</table>";
try this
echo '<table>';
while($rows = mysql_fetch_array($result)){
echo '<tr><th>'.$rows['product_name'].
'</th></tr><tr><td>'.$rows['id'].
'</td></tr><tr><td>'.$rows['product_type'].
'</td></tr>';
}
echo' </table>';

Categories