Nested while loop is not working as expected - php

I'm having a problem in php. I tried to show all data and then put them in a nested loop. but the second loop only returns nulls. I don't know what I did wrong.
<?php
ini_set('max_execution_time', 36000);
$con=mysqli_connect("localhost","root","XXX","YahooFin");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"show tables from yahooFin where not tables_in_yahooFin = 'nasdaqCompanyList' and not tables_in_yahooFin = 'companylist'");
while($row = mysqli_fetch_array($result)) {
$result2 = mysqli_query($con, "select * from ".$row['Tables_in_yahoofin']." where entry_date = '2013-06-03'order by entry_date asc limit 1");
while ($row2 = mysqli_fetch_array($result2)); //<== This line gives me null
{
var_dump( $row2);
echo "<br>";
}
}
var_dump($row);
mysqli_close($con);
?>

There is an extra ; semicolon which shouldn't be there after your loop
while ($row2 = mysqli_fetch_array($result2)); //<== This line gives me null
//^ remove this one
Also You probably have a typo tables_in_yahooFin is used in first query while Tables_in_yahoofin is used in second.

Related

mysqli_fetch_array only displays the first result

I struggled all day to display the results of an SQL query using PHP.
I have a table in the database named coins with the following columns:
- nr_unic (which is the index);
- rank;
- name;
- symbol;
- price_usd;
- price_btc;
What I need to do is to fetch the values of each coin (from the name field) and display the symbol, price_usd, price_btc, and rank. The piece of code which contains the query I am running and trying to display the values is:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// SQL QUERY
$sql= "SELECT rank, name, symbol, price_usd, price_btc, 24h_volume_usd FROM coins WHERE rank BETWEEN 1 AND 10 ORDER BY nr_unic DESC LIMIT 10";
$result = $conn->query($sql);
$rows = array();
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . $row['price_usd'] . " " . $row['symbol'] . " " . $row['rank'];
foreach ($rows as $key => $value) {
echo $value;
}
}
mysqli_free_result ($result);
}
Thank you!
LATER EDIT
Following #Máté Solymosi indications I managed updated the code and to display the results. The problem now is they are getting duplicated: I get the first coin, then the first and the second, then the first, second and third... and so on.
The code I use was updated
The return statement in your while loop causes the function to terminate immediately, returning just the first row. Instead, you should collect the results in an array and return the array at the end:
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . // ...
}
mysqli_free_result($result);
return $rows;

Get top 4 highest rows based on ID

I'm trying to grab the highest 4 rows in a table and assign variables to them so that I can use them throughout my code.
Here is what I was able to get so far...
<?php
$username="USERNAME";
$password="PASSWORD";
$database="DATABASE";
$conn = mysqli_connect(localhost, $username, $password, $database);
$query = "SELECT * from `shoutbox` ORDER BY `id` DESC LIMIT 4";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
$name =($row["name"]);
$message =($row["message"]);
$time =($row["time"]);
}
?>
How am I able to assign more variables to get the next 3 rows?
I believe it's (sorry, long day so I might be off)
$result = array();
while(...){
$result[] = $row;
}
I suggest you loop through the result set and assign each iteration to an array, you can then pull the values back out of the array later.
Here is a working update to your code
// ...
$query = "SELECT * from `shoutbox` ORDER BY `id` DESC LIMIT 4";
$result = $conn->query($query);
// create array to hold queried result set
$output = array();
// loop through result set and assign each row to a key in $output array
// Note: the fetch_assoc() method auto-increments an internal pointer
// so as you spin through the result set $row will move down the rows
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
// $output now contains an associative array on each key representing
// each row, so to access each row:
foreach($output as $row) {
echo $row["name"] . "<br>";
echo $row["message"] . "<br>";
echo $row["message"] . "<hr>";
}
Define $result as array after while
$result = array();
while($row= .... ){
$var= $row['name'];
.............
}

How to Select Specific Info From MySQL

I'm trying to a number from a specific table, row, and column but can't seem to get it right.
The table is tblproducts. The column is qty. And I need to select where id is 13.
This is the code I'm using but it isn't returning anything:
<?php
$con=mysqli_connect("localhost","blank","blank","blank");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT qty FROM tblproducts");
while($row = mysqli_fetch_array($result))
{
echo $row['13'];
}
mysqli_close($con);
?>
Any help would be appreciated
do it all in the query like so
SELECT qty FROM tblproducts where id =13
no loop needed
$result = mysqli_query($con,"SELECT qty FROM tblproducts where id =13");
$row = mysqli_fetch_assoc($result);
echo $row['qty'];
Your sql syntax is a bit off, see my corrections. Your echo of the row['13'] also looks suspicous. You can use print_r() to print arrays to find which key you need to use. It is probably $row['qty'].
<?php
$con=mysqli_connect("localhost","blank","blank","blank");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT qty FROM tblproducts where id = 13");
while($row = mysqli_fetch_array($result))
{
print_r($row); // You can use print_r to have a look at your full array. The index '13' might not be what you where looking for.
}
mysqli_close($con);
?>

How to retrieve sum of a column in PHP

Hi I have a query in PHP that calculates the sum of all the values in a column. However when I try to print, nothing happens. I get a blank page. Im pretty sure its an obvious problem but constant coding means I cant think straight :(
$query = 'SELECT SUM(cost) AS total_price FROM items WHERE item_ID = $input';
$sum = mysql_query($query, $database);
$row = mysql_fetch_row($sum);
echo "Total "" = $". $row['total_price'];
mysql_fetch_row fetches a enumerated array, you want mysql_fetch_assoc.
Alternatively you can just use mysql_result to fetch the single field.
You also have a syntax error in your echo which would cause a blank page unless you have error_reporting/display_errors on:
echo "Total "" = $". $row['total_price'];
should be:
echo "Total = $". $row['total_price'];
Try this
$query = 'SELECT SUM(cost) AS total_price FROM items WHERE item_ID = $input';
$sum = mysql_query($query, $database) or die(mysql_error());
if(mysql_num_rows($sum) > 0) {
$row = mysql_fetch_assoc($sum);
echo 'Total = $'.$row['total_price'];
} else {
echo "No result found";
}

PHP - how to print each row of an array

I feel like I'm missing something really simple here. Here's my sql query:
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
I then print the first result:
echo $row[0];
And get a correct value, the id of the first page (by page order):
10
So I submit a form which simply turns that $row[0] into $row[1].
And nothing prints. I don't understand.
You have to do this:
while ($row = mysqli_fetch_array($showpages, MYSQLI_NUM)) {
$id = $row[id];
// do something with the id
echo $id . "<br/>"; // Echo every id
}
This will iterate through all of the results
mysqli_fetch_array is a special function as each time you call it, it outputs the NEXT row.
So:
while ($row = mysqli_fetch_array(stuff)){
$var = $row['sql column'];
// In your case "$var = $row[0];" to get the id for the first row found.
}
is how you use it.
This will keep running the function until mysqli_fetch_array() eventually returns false. These each time it will output a new row. And the $row array is the array of one row in the sql table.
Use :
print_r($row);
in the while loop to see exactly what's being returned for use.
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
Question how many rows are fetched in this query in this case id, So MYSQL will result to 1 row affected, But since you are using
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
This code you used will not output anything try
$row[n] as n-1
$result->fetch_assoc() or mysqli_fetch_assoc($result)
catch one line at a time, from a mysqli_result:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
source: http://www.w3schools.com/php/php_mysql_select.asp

Categories