PHP - how to print each row of an array - php

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

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;

Getting number of rows form SQL Server table

I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.

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";
}

What would MySQL statement be if looking up details from a unique ID in my database?

I want to print out details from the database with a unique ID which is taken from the URL.
I've used the $_GET array to get the event ID from the URL, but how would i look up the details of that event in the SQL statement? I've attempted it below but i don't think it's right. When I run the code, the page comes up blank.
<?php
$eventID = clean_string($db_server, $_GET['eventid']);
$query = "SELECT eventname, eventimage, eventdate FROM events WHERE eventID=$eventID";
$result = mysqli_query($db_server, $query) or die(mysql_error($db_server));
if (!$result) die('Query failed: ' . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
}
mysqli_free_result($result);
?>
mysqli_query returns a mysqli_result object.
mysqli_fetch_array returns the result rows as both an associative or a numeric array.
TRY
// Numeric array
while($row = mysqli_fetch_array($result)){
echo $row[0];
echo $row[1];
//etc
}
// Associative array
while($row = mysqli_fetch_array($result)){
echo $row["eventname"];
echo $row["eventimage"];
//etc
}

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.
}

Categories