mysqli_fetch_array only displays the first result - php

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;

Related

Looping mulitple SQL queries in multiple arrays

I'm a PHP beginner. I've dabbled before, but when I've begun to get the knack a new project takes me elsewhere. If anyone can assist; I'd appreciate it.
I am using multiple queries and arrays to retrieve data between two mySQL tables starting from 1 initial known variant.
I'd like each query to process all results from the previous query. This is not occurring.
Current results: The first query echos all results. The second query echos one result. The third query echos 1 result. The final echo displays all the final results (desired, but missing the first 148 rows).
Desired results: Echo all 149 results from all three queries then echo a table/array of all 3 queries (to confirm correlation).
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Select all POST_IDs for variation 2.1M
$sql = "SELECT post_id FROM wp_postmeta WHERE meta_value = '2-1m'";
$result = $conn->query($sql);
//Array and display POST_IDs
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["post_id"]. "<br>";
}
} else {
echo "0 results";
}
//Prepare POST_IDs for next query
foreach ($result as $row){
$postids = $row["post_id"];
}
//Use POST_IDs to select all PARENT_IDs
$sql2 = "SELECT post_parent FROM wp_posts WHERE ID = ($postids)";
$result2 = $conn->query($sql2);
//Array and display PARENT_IDs
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
echo "parentid: " . $row2["post_parent"]. "<br>";
}
} else {
echo "0 results";
}
//Prepare PARENT_IDs for next query
foreach ($result2 as $row2){
$parentids = $row2["post_parent"];
}
//Select PRICES using PARENT_IDs and META_KEY for Price
$sql3 = "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_price' AND post_id = ($parentids)";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
// output data of each row
while($row3 = $result3->fetch_assoc()) {
echo "price: " . $row3["meta_value"]. "<br>";
}
} else {
echo "0 results";
}
//Array and display PRICES
foreach ($result3 as $row3){
$prices = $row3["meta_value"];
}
//Display all retrieved data
echo "<div><p>" . $postids . " " . $parentids . " " . $prices . "</p></div>";
$conn->close();
?>
You're overriding your variables instead of cumulate them into an array:
foreach ($result as $row){
$postids = $row["post_id"];
}
Should be :
$postids = [];
foreach ($result as $row){
$postids[] = $row["post_id"];
}
Then :
"WHERE ID = ($postids)"
Should be :
if (!empty($postids)) {
... "...WHERE ID IN (".implode(',', $postids).")..." ...
}
NB: you should have a look to parameterized queries : Parameterized Queries PHP/MySQL
The same thing happend for $parentids.

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'];
.............
}

Grabbing more than just one row from DB

$sql = "SELECT title, article, filename, caption FROM articles
INNER JOIN images WHERE articles.image_id = images.image_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
var_dump($row);
This only grabs the first row in the db when what I need is for it to grab all rows. How can I achieve this?
fetch_assoc() returns the next row of the result set with each call, so you need to call it in a loop like this:
while($row = $result->fetch_assoc()) {
var_dump($row);
}
The loop ends when $row = null (i.e. there's no more rows in the result set).
Please have a look at the Quick start guide, more specifically the Executing statements chapter. Right from that page:
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}

Whats wrong with the syntax in my mysql select statement (php, mysql)

I have a table and i'm trying to extract the maximum value of a column called order_num, which has 33 intries of integers 1 through 33. I want the value "33" in this instance as its the highest number.
$userid is an integer derived from a one row table with a field id that I am trying to retrieve
//get the currentUser ID so we know whos deck to ammend
$userIDSQL = "SELECT id FROM currentUser";
$userIdResult = mysqli_query($db, $userIDSQL) or die("SQL Error on fetching user ID: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_assoc($userIdResult)) {
$result_array[] = $row['id'];
}
//the actual user id
$userId = $row['id'];
echo "user id is " . $userId;
Doing a print_r on $userId shows the array to be empty, that's why the code below doesn't work.. :(
...
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
$result_array[] = $row['MAX(order_num)'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
echo "the result is" . $result_array['MAX(order_num)']; //tried different methods to get the output.
}
The output I get is
the result is the result is the result is
Does anyone know why i'm not able to get the result from the table?
Edit:
Okay, try this:
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
print_r($row);
}
What do you get?
Your first code to get the userId doesn't work because of your usage of the array, change to:
$userId = 0;
while ($row = mysqli_fetch_assoc($userIdResult)) {
$userId = $row['id'];
}
As I've shown below, if you only expect a single row then remove the while loop and just call fetch_assoc a single time.
Given you only want the single row you don't need the while loop:
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId' LIMIT 1";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
if($reOrderDeckResult && mysqli_num_rows($reOrderDeckResult) == 1)
{
$row = mysqli_fetch_assoc($reOrderDeckResult);
echo 'result: ' . $row['order_num'];
}
else
{
echo 'No rows found!!';
}
I also added LIMIT 1 to the query, and a check to see if there are any rows.
You have renamed your MAX(order_num) AS order_num so you should try to get value using order_num only as echo $result_array['order_num']
and in while you should check whether you are getting value or not by placing below code in while loop
echo '<PRE>';
print_r($row);
echo '</PRE>';
This may helps you..,
<?php
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
//you have to use the alias name not aggregate function title
$result_array[] = $row['order_num'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
//you have to use the alias name not aggregate function title
echo "the result is" . $result_array['order_num']; //tried different methods to get the output.
}

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