Creating html list from php array - php

I am trying to create a html list from a php array that I've fetched from a SQL query, but no matter what I just get really weird results.
$dbf = mysql_query("SELECT * FROM testdb") or die(mysql_error());
$info= mysql_fetch_array($dbf);
foreach($info as $x)
{
echo '<li>' . $x['name'] . '</li>';
}
Instead of getting the names in my database I get the following values
a
a
d
n
k
I am probably doing something wrong?

In your code, you are performing mysql_fetch_array($dbf) function only once. This only selects the first row from your result set. What you need to do is send this function as a condition on a while loop. Consider the following alterations on your code:
$dbf = mysql_query("SELECT * FROM testdb") or die(mysql_error());
echo '<ul>';
while( $info = mysql_fetch_array( $dbf, MYSQL_ASSOC ) )
{
echo '<li>' . $info[ 'name' ] . '</li>';
}
echo '</ul>';
In the above code, your while loop iterates through each and every tuple that your SELECT query produces. That should solve your problem.

The problem is mysql_fetch_array() only fetches the first row from the result set.
You need to execute mysql_fetch_array in a loop.
while($info= mysql_fetch_array($dbf))
{
echo '<li>' . $info['name'] . '</li>';
}

Related

Why is only the first record being returned from this PHP array?

I'm trying to return four records from my MySQL database but only the first record is being returned. I've searched but I'm unsure why this is. Can someone point me in the right direction?
<?php
session_start();
function displayImage($username){
$imageDate = $_POST['imageDate'];
$result = mysql_query("
SELECT
imageName
FROM
images AS i
INNER JOIN
users AS u ON i.userID = u.UserID
WHERE
u.username = '$username'
AND
i.imageDate = '$imageDate'
") or die(mysql_error());
//return a message to the users explaining ......
if (!isset($_POST['Submit'])) {
// this does nowt yet!!!
$output = "Nothing selected yet.";
}
else {
//This is a while loop to store the SQL results into ......
$row = array(mysql_fetch_assoc($result));
foreach ($row as $picName) {
$cam = $_POST['cam'];
$fullPath = $username . "/" . $cam . "/" . $picName['imageName'];
// $output = //this works fine
reset($images);
}
}
var_dump($row);
echo "<br />";
return $output;
}
?>
You should use loop to fetch result:
while ($row = mysql_fetch_assoc($result)) {
$cam = $_POST['cam'];
$fullPath = $username . "/" . $cam . "/" . $row['imageName'];
}
As others here have said, you need to use a while loop for this, I've tidied the code up a tiny bit and added a couple of other things for you to consider.
The actual reason for this is that when you use mysql_fetch_assoc it brings back one result resource and removes it from resources it has left to return. So if you just try and store it in an array, you get the first one in the array, and nothing else. When you use a while loop it works by basically saying "if mysql_fetch_assoc has something to give, then do the code inside the loop".
<?php
session_start();
function displayImage($username) {
// Also, as others have said, check out PDO, or MySQLi, as they
// both provide a better interface with MySQL an have better
// security features.
$username = mysql_real_escape_string($username);
$imageDate = mysql_real_escape_string($_POST['imageDate']);
$result = mysql_query("
SELECT
imageName
FROM
images AS i
INNER JOIN
users AS u ON i.userID = u.UserID
WHERE
u.username = '$username'
AND
i.imageDate = '$imageDate'
") or die(mysql_error());
//return a message to the users explaining
if (!isset($_POST['Submit'])) {
// this does nowt yet!!!
$output = "Nothing selected yet.";
} else {
$cam = $_POST['cam'];
$images = array(); // This is part of the "you could do something
// like" further down.
while ($row = mysql_fetch_assoc($result)) {
$fullPath = $username . '/' . $cam . '/' . $row['imageName'];
// $output = //this works fine
var_dump($row);
echo "<br />";
// Or you could do something like:
$images[] = $username . '/' . $cam . '/' . $row['imageName'];
// Then outside of this while loop you'd have all of your image
// paths stored in this $images array.
//
// It depends on how you want to handle outputting them.
}
}
return $output;
}
The comments in the code go through my main points.
I also moved that $cam = $_POST['cam'] from inside of the loop, to outside of it, as it doesn't need to go in the loop because it's value will always be the same, regardless of which loop item you're going over.
The way to use mysql_fetch_assoc or mysql_fetch_array is this:
while ($row = mysql_fetch_assoc($result)) {
// This is an example...
echo $row["id"];
echo $row["name"];
}
If you still need an explanation:
1. Why you got only one record??
When you declare:
$row=array(mysql_fetch_assoc($result));
This means that you get one record from the database, the mysql_fetch_assoc() method was run only once, so your method calls 1 row from the database table.
2. How to get this to work?
Like you have seen in the example given by others, use a while loop instead.
2.1 How does the loop work?
When you call:
while (<some command1 equates to true or false>) {<some command2>}
At first they run somecommand1. If it returns true, do some command2. After command2 has finished, run somecommand1 again. If it still true, do somecommand2 and so on... A nice example is the command you're using.
while ($row = mysql_fetch_assoc($result))
{
echo $row['fieldname1'];
echo $row['fieldname2'];
}
In this loop $row = mysql_fetch_assoc($result) is Somecommand1 as explained. This function returns a resource which equates to true if there is another row returned from the database. After one run through of the code within the while loop it skips onto the next row. Then it re-runs the mysql_fetch_assoc function. If there is still some record in the table that matches the query, this function will still do whatever is in your while loop.
If you need more examples, take a look at w3schools.com. I started PHP from there.

mysql_fetch_array to compare data between 2 tables using php?

I'm attempting to utilize 2 mysql tables via php/mysql 2 get me a max value. I'm assuming using an array is the correct way to do this, but I've been spending many hours and am missing something.
My tables are:
1) plantcomp, where I want to know all the CompressID listings that have a CustID of $CustID. (there are currently 3).
2) comps, where I want to use those CompressID listings to know the valid Compressor #s. I'll then do a max() on those values so I can name the next compressor max()+1.
My code attempts...This gets me an error: "Notice: Array to string conversion in (pathname) on line 55", then "Array"
//have the custid
echo $CustID;
//under table `plantcomp`, find matching compressid's.
$q55 = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
// Run query
$result55 = mysql_query($q55);
while($row = mysql_fetch_array($result55)){
echo "<p>".$row;
I also tried this, mysql_fetch_assoc, but it only gives me 2 of my 3 valid entries...
$get = mysql_query("SELECT CompressID FROM plantcomp WHERE CustID = '$CustID'");
$money = mysql_fetch_assoc($get);
while($money = mysql_fetch_assoc($get)){echo $money['CompressID'];}
Thank you in advance for your assistance!!
Please change this line
echo "<p>".$row;
to
echo "<p>";
print_r($row);
The problem you have comes from the fact that you are mixing a string (<p>) with an array ($row).
echo "<p>".$row;
You can print the $row array by using print_r:
print_r($row);
You can also access different elements of the $row array (table columns) like this:
$row['column_name'];
For example, lets say your table consists of two columns: first_name and last_name. You can print them like this:
echo '<p>' . $row['first_name'] . ' ' . $row['last_name'] . '</p>';
So, with that knowledge, we can print your CompressIDs:
$result55 = mysql_query("SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "'");
while ($row = mysql_fetch_assoc($result55))
{
echo '<p>' . $row['CompressID'] . '</p>';
}
$CompressID = array(); //Initialising an array
$query = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
$result = mysql_query($query);
while($obj = mysql_fetch_assoc($result)){
$CompressID = $obj['CompressID']; //Storing all the CompressID in an array
echo $obj['CompressID']; // sanity check
}
First run the above query and compare result with db.If the result is not matching
1)There is some wrong data in db
2)Alter your query to get desired result.
If this is working then add rest of the code
if( count($CompressID) >0 ){
$query = "SELECT max(CompressID) as maxCompressID FROM `comps` WHERE `CompressID` IN($CompressID)";
$result = mysql_query($query);
while($newObj = mysql_fetch_assoc($result){
echo $newObj['maxCompressID'];
}
}

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

How to retrieve and display an array with objects from php cell using a loop?

In a Flex project, I have an array with objects in it. I want to save this array in a cell on a mysql table along with some other basic info like title, and an id.
EDIT: just clarifying since i seem to be getting responses explaining how to echo all the rows... I'm trying to echo the contents of an array that was serialized and placed in a single cell. This array has objects in it.
So, I have this code here to serialize the array, and insert it along with the other info into my DB:
function submitLogDbObj($array,$id,$title)
{
$title=mysql_real_escape_string($title);
return mysql_query("INSERT INTO logs (text,id,title) VALUES ('".serialize($array)."','$id','$title')");
}
Then for a test i'm trying to make a loop that will display the log in a way that looks like a conversation...
an object in my array would look something like:
[1]
icon = ""
msg = "this is a test"
name = "Them: "
systemMsg = 0
[2]
icon = ""
msg = "yep it sure is"
name = "You: "
systemMsg = 0
So here's what i've got so far, but its not working! How can I make a loop that will take that array from the DB, unserialize it and then echo the convo in a way that looks like a chat log?
Thanks!
<?php
include_once("dbinfo.php");
$id= $_GET['id'];
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($result)
{
$log = unserialize($row['text']);
echo 'starting loop!';
echo "<ul>";
/* im not sure how to represent the length of an array in php thats why i just have $log.length */
for ($i = 1; $i <=$log.length; $i++)
{
echo "<div id='logbox'>";
echo "<li>";
$name=$log[$i]['name'];
$msg=$log[$i]['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
echo "<br />";
}
echo "</ul>";
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Well, there're a few things which could be better here:
The length of an array is found through count( $array ) or sizeof( $array )
$value . $otherValue means concatenate those two values. Since length is undefined in this context, $log.length means "$log.length".
The best way to loop through an array is foreach( $set as $val) or foreach( $set as $key => $val )
The preferred method of iterating through a SQL result is the while loop: while($row = mysql_fetch_array($result)){ or do... while (see below). Unless you specifically and consciously only want one, then it would be best to use that. And if you do only want one, then put a Limit in the query.
Serialized arrays in databases has a redundant flavor. Are you sure that this is what you want?
Your serialized array, before it is inserted, should also be run through mysql_real_escape_string.
br really shouldn't be needed if you're surrounding something in its own div.
Indent properly or the kitten of death will come for you.
The improved code:
$row = mysql_fetch_array($result);
// row could be empty if there were no results
if($row)
{
// we've already grabbed the first value, so we need
// to invert while into do... while.
do
{
$log = unserialize($row['text']);
echo "<ul>";
foreach( $log as $line )
{
// Are you sure this should be outside of the li?
echo "<div id='logbox'>";
echo "<li>";
$name=$line['name'];
$msg=$line['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
}
echo "</ul>";
}
while( $row = mysql_fetch_array($result) );
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Firstly, get into the habit of indenting your code properly, it will save you a lot of frustration when looking for errors.
You don't need to know the length of the array, you can just use a while loop: (coding from the hip here so let me know if you get errors)
$result = mysql_query("......") or die("Query failed");
//Keep going while $row isn't FALSE
//mysql_fetch_array returns false when there are no more rows
while($row = mysql_fetch_array($result)){
//You can close PHP tags here and insert the
//variables in the HTML, it often looks neater
//and your editor can colour code HTML, helping
//you to find problems
?>
<div>
<li><?php echo $row['name'] ?></li>
<li><?php echo $row['msg'] ?></li>
</div>
<?php
}
See the "fetch array while loop" of this tutorial for more examples.
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
echo "<ul>";
while ($row = mysql_fetch_assoc($results)) {
$name = $row['name'];
$msg = $row['msg'];
//display data how ever you want
}
echo "</ul>";

Looping through an array and querying data

Basically what I'm trying to achieve is go through an array and do a query based on that data - e.g. array of names bob, bill, ben and query a database table based on all of the items in the array - so SELECT * FROM table WHERE name="$name".
The code I have is:
<?php
session_start();
$array = $_SESSION['basket'];
foreach ($array = $_SESSION['basket'] as $value);
$query = "SELECT * FROM catalogue WHERE plantname='$value'";
$result = mysql_query($query) or die("Query failed : " . mysql_error());
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
?>
but this is only displaying the last item it should be picking out of the query, any help is much appreciated.
The problem is with this line
foreach ($array = $_SESSION['basket'] as $value);
$query = "SELECT * FROM catalogue WHERE plantname='$value'";
First is the semicolon - it shouldn't be there. Also notice that you have no { } around your foreach statement, so you build a query for each item in your session variable, but execute it only for the last one.
To get everything for all the possible $values, which is what I think you're trying to do, you want something like this:
SELECT * FROM catalogue WHERE plantname IN ('value1', 'value2')
Which can be accomplished with something like:
$query = "SELECT * FROM catalogue WHERE plantname IN ('" . implode($array, "', '") . "')";
...without hitting the database multiple times.
UPDATED: Moved query outside of loop.
<?php
session_start();
$array = $_SESSION['basket'];
$query = "SELECT * FROM catalogue WHERE plantname IN ('" . implode("', '", $array) . "')";
$result = mysql_query($query) or die("Query failed : " . mysql_error());
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
?>
There are a number of issues in your code.
Firstly you have already assigned to $array so you only need to do:
foreach($array as $value)
Secondly you shouldn't be running queries inside a loop, as the basket gets bigger the more queries are executed on every page request.
Why not push the row into $_SESSION['basket'] then you can just loop $_SESSION['basket'] to show it rather than running loads of queries, it will make your code execute faster and you'll right less code.
Also be careful with the other answers as they haven't considered security as database input should be escaped.

Categories