Failed to iterate over selected rows - php

The code is supposed to get a row at each loop and build td elements for each data piece. However, it only gets some rows while missing others even though all rows were selected:
$query = "select * from category";
$ret = mysql_query($query, $conn);
while ($rows = mysql_fetch_assoc($ret)) {
echo "<tr>";
foreach ($rows as $val) {
echo "<td>{$val}</td>";
}
}

mysql_fetch_assoc returns an associative array. To display each returned row, do something like this (taken directly from the php.net page for mysql_fetch_assoc
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}

Try removing the curly braces like this:
echo "<td>$val</td>";
Beside you didn't close the <tr> tag. So you should do this:
$query = "select * from category";
$ret = mysql_query($query, $conn);
while ($rows = mysql_fetch_assoc($ret)) {
echo "<tr>";
foreach ($rows as $val) {
echo "<td>$val</td>";
}
echo"</tr>";
}
Now like Jack Albright said you should consider various columns of your table to display specific data. Upon that the while() is already a look, I think you don't need to add any foreach() inside. SO your final code should look like this:
$query = "select * from category";
$ret = mysql_query($query, $conn);
while ($rows = mysql_fetch_assoc($ret)) {
echo "<tr>";
echo "<td>$rows['columnName']</td>";
echo "</tr>";
}

Related

Get an array of rows from a MySQL query?

I have this code...
$results_query = "SELECT * FROM profile WHERE string LIKE '%" . $search_deliminator . "%'";
$results_result = $database->query($results_query);
$result = mysql_fetch_array($results_result);
What I'm trying to do is pull all the rows in which the string column contains my search deliminator. Further, I would like to get the values from each column of the rows.
How would I pull the multidimensional array I need containing each row, and each value of each column within each row?
EDIT:
I'm looking to do something to this effect...
while ($row = mysql_fetch_assoc($results_result)) {
$result[] = $row;
}
Then echo each column like this...
foreach ($result as $row) {
echo $row["0"];
}
To get a flattened array of the result set, try this:
$result = array();
while ($row = mysql_fetch_assoc($results_result)) {
$result[$row['id']] = $row;
}
echo json_encode($result);
Also, you should look into either MySQLi or PDO to replace the (now deprecated) MySQL extension.
If you use PDO, you can use the fetchAll() method:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
With mysql or mysqli, you use a loop:
$rows = array();
while ($row = $stmt->fetch_assoc()) {
$rows[] = $row;
}
try this
$i=0;
while ($row = mysql_fetch_assoc($results_result)) {
$result[$i]["column1"] = $row["column1"];
$result[$i]["column2"] = $row["column2"];
$i++;
}
To display the output use:
foreach ($result as $row) {
echo $row["column1"];
echo $row["column2"];
}

retrieve from all row and display it

$query = "SELECT * FROM main";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc()) {
$name= $row["name"];
$image = $row["image"];
}
}
then somewhere in my code I print it out using like echo $name; but I got only one result, which is the last row. I know I have to do foreach but what variable should I put?
foreach($result as $results) ? like this?
On every iteration, you reassign the values to $name and $image, causing it to show only the last value when it leaves the loop.
You can either echo them right away in the loop, or populate an array or an object with them, so they will be available later.
Example:
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = array('name'=>$row["name"], 'image'=>$row["image"]); // push into the array
}
var_dump($data); // it's all here now
And to echo the data later, one of the ways is foreach:
foreach($data as $row) {
echo "Name: ", $row['name'], "; Image: ", $row['image];
}
$query = "SELECT * FROM main";
$result = $db->query($query);
$row = $result->fetch_assoc();
foreach ($row as $rows) {
echo $rows['name'] ." ". $rows['image'];
}

php query adding a div between every third item echod to page

I cant seem to figure out how to implement any examples I found online of how to us a counter so that ever 3rd echo of " $row['item']" has a div in between it.
$result = mysql_query("SELECT * FROM table")
while($row = mysql_fetch_array( $result )) {
echo $row['item'] ;
}
When you want to do something every x loops, I find the easiest method is to use a modulo/modulus operator:
for($i=0;$i<20;$i++)
{
if($i%3==0)
{
echo "This is the third time round...";
}
}
you can easily implement this into a loop while fetching rows from the database.
$result = mysql_query("SELECT * FROM table")
$i=0;
while($row = mysql_fetch_array( $result ))
{
echo $row['item'] ;
if($i%3==0)
{
echo "Do your DIV stuff here...";
}
$i++;
}
Try
$result = mysql_query("select * from table")
$i=0;
while($row = mysql_fetch_array( $result ))
{
echo $row['item'] ;
if($i%3==0)
{
echo "<div>Your div content</div>";
}
$i++;
}
I would also suggest to go through for/while/foreach loop as well

Joining two different tables containing csv and display them on a webpage

I have been stuck with a problem and I am newbie in mysql and php, Here is the code first , so that I can explain in detail:
$metros = array(1,263);
foreach($metros as $metro_id) {
$sql = "SELECT cuisine_id, cuisine_name_en FROM poi_restaurant_cuisines";
$result = mysql_query($sql);
$cuisine_id = array();
$cusine_name = array();
while($row = mysql_fetch_assoc($result)) {
$cuisine_id[] = $row['cuisine_id'];
$cuisine_name[] = $row['cuisine_name_en'];
}
foreach ($cuisine_id as $cuisine) {
$sql = "
SELECT COUNT(*)
FROM poi AS p
LEFT JOIN poi_restaurant AS pr USING (poi_id)
WHERE p.poi_address_prefecture_id = '$metro_id'
AND pr.poi_restaurant_cuisine_id_array
AND find_in_set('$cuisine', poi_restaurant_cuisine_id_array)
AND p.poi_status = 1";
$result = mysql_query($sql);
$count_cuisine = array();
while($row = mysql_fetch_array($result)) {
$count_cuisine[$metro_id][$cuisine] = $row['COUNT(*)'];
}
echo "<table border = 1 cellpadding= 5 cellspacing= 5 width= 100>";
echo "<tr><th>CuisineID</th><th>Count</th></tr>";
echo "<tr><td>";
echo $cuisine;
echo "</td><td>";
echo $count_cuisine[$metro_id][$cuisine];
echo "</td><td>";
echo "</tr>";
echo "</table>";
}
}
The poi_restaurant_cuisine_id_array contains csv values. I am able to produce the count and the cuisine ID on the web page. I want to replace the cuisine ID with the name of the cuisine. I am not very good at sql or either PHP as I am a beginner. I hope I am being clear enough. Any help is highly appreciated ...Thank you.
Try this:
echo '<table border="1" cellpadding="5" cellspacing="5" width="100">';
echo "<tr><th>Cuisine</th><th>Count</th></tr>";
$metros = array(1,263);
foreach($metros as $metro_id) {
$sql = "SELECT cuisine_id, cuisine_name_en FROM poi_restaurant_cuisines";
$result = mysql_query($sql);
$cuisines = array();
while($row = mysql_fetch_assoc($result)) {
$cuisines[] = array(
'id' => $row['cuisine_id'],
'name' => $row['cuisine_name_en'],
);
}
foreach ($cuisines as $cuisine) {
$sql = "
SELECT COUNT(*)
FROM poi AS p
LEFT JOIN poi_restaurant AS pr USING (poi_id)
WHERE p.poi_address_prefecture_id = '$metro_id'
AND pr.poi_restaurant_cuisine_id_array
AND find_in_set('{$cuisine['id']}', poi_restaurant_cuisine_id_array)
AND p.poi_status = 1";
$result = mysql_query($sql);
$count_cuisine = array();
while($row = mysql_fetch_array($result)) {
$count_cuisine[$metro_id][$cuisine['id']] = $row['COUNT(*)'];
}
echo "<tr>
<td>{$cuisine['name']}</td>
<td>{$count_cuisine[$metro_id][$cuisine['id']]}</td>";
</tr>";
}
}
echo "</table>";
Assuming cuisine_id is a unique identifier, then just use it as the array index....
while($row = mysql_fetch_assoc($result)) {
$cuisines[$row['cuisine_id']] = $row['cuisine_name_en'];
}
....
foreach ($cuisines as $cuisine_id=>$cuisine_name_en) {
However storing multiple values in a single column is a very bad idea.
Generating and running queries in a loop is another very bad idea.
It is possible to reduce this to a single query, declared and invloked outside the inner loop but because your data is not mormalized, this is rather complex.

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