Loop Through Array using PHP and MySQLi [duplicate] - php

This question already has answers here:
How to loop through a mysql result set
(6 answers)
Closed 3 years ago.
I'm trying to loop through a MySQL table using PHP, but it is only showing one line.
//Retrieve a list of outstanding developments
$sql = "SELECT * FROM tblDevelopment WHERE strStatus=?";
$statement = mysqli_stmt_init($conn);
//Check for any errors in the SQL statement
if (!mysqli_stmt_prepare($statement,$sql)){
//Report any errors with the prepared $statement
header("Location: ../sqlerror.php");
exit();
} else {
//If there are no errors, query the database for the username
mysqli_stmt_bind_param($statement,'s', $status);
mysqli_stmt_execute($statement);
$results = mysqli_stmt_get_result($statement);
if ($row = mysqli_fetch_assoc($results)) {
echo 'header';
while ($row = mysqli_fetch_assoc($results))
{
echo $row['strDetail'] . "</";
}
echo 'footer';
} else {
echo 'No results to display';
}
}
The code works when there are no results, but it only shows one result when there are more than one - any ideas what I'm doing wrong?

You are almost there... you need to keep calling mysqli_fetch_assoc until you reach the end of the result set. Changing your if to a while should be enough to get you rolling.
while (($row = mysqli_fetch_assoc($results)) !== null) {

Related

How do I get a value outside the loop using PHP [duplicate]

This question already has answers here:
How to get comma separated values from database [duplicate]
(3 answers)
Converting MySQL results into comma separated values
(4 answers)
Can I concatenate multiple MySQL rows into one field?
(16 answers)
Closed 3 years ago.
I'm creating a small website using PHP, which is generally a site for showcasing the hospital, and I modified the code given in this example:
https://www.w3schools.com/php/php_mysql_select.asp
<?php
$query = "SELECT * FROM emp WHERE type = 'woman' ";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$cat = $row["cat"] . ',';
echo $cat;
////<---- echo on while (Loop)
}
}
The expected output would be as follows:
Output: 35,36
But I changed the code with the link above and it is as follows:
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$cat = $row["cat"] . ',';
}
echo $cat;
///// <---- echo Out of While (Loop)
}
Output: 35
My expecting output would be 35, 36 outside of "while" using "echo".
What code do you recommend to output "35,36" the same code above?
You can try the below code to achive your requirement
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result)) {
$data[] = $row["cat"];
}
}
echo implode(",",$data);

Display the results of a query if the query is executed [duplicate]

This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
What I am trying to do is get the values of the $r variable (returns some vehicle id values) to display on the page. However, it returns the following error.
Recoverable fatal error: Object of class mysqli_result could not be
converted to string in
C:\xampp\htdocs\SAMADHI\system\module\reservation\controller\reservationcontroller.php
on line 166
The problem is on the echo $r statement. I tried echo '$r' but then it shows nothing even though it displays the the message 'vehicle available'.
if ($nor > 0) {
$r = $objs->searchVehicle($vhandover, $vreturn, $seatcap);
if ($r) {
$msg = "Vehicle available";
$status = 1;
echo $r;
} else {
$msg = "Something is not right!";
$status = 0;
}
}
What am I doing wrong here and how can I correct it?
Let me assume, your vehicle table have following column - id, name, type. When your query executes, $r holds an associative array with search result-
$r = [ ['id'=>1, 'name'=>"toyota", 'type'=> "regular"], ....]
This is not any String. So if you want to echo any of the column value you need to mention it like -
echo $r['name'];
But if your query returns multiple results then, you need to put the echo inside a foreach loop.
foreach($r as $row) {
echo $row['name'];
}
UPDATE
If the above code doesn't work for you then try the following-
while($row = $r->fetch_assoc()) {
echo $row['id'];
}
UPDATE: 2
You can use fetch_array($r) -
while ($row = fetch_array($r)) {
echo $row['name'];
}
Hope that clears your concept!

SQL select as a PHP function [duplicate]

This question already has answers here:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in
(3 answers)
Closed 7 years ago.
I'm selecting data from MySQL. My code looks like this:
$sql = "SELECT oznacenie_odpadu FROM zdroj_dat ORDER by ID ASC";
if ($result = $conn->query($sql)) {
// fetch associative array
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row['oznacenie_odpadu'].'" >'.$row['oznacenie_odpadu'].'</option>';
}
}
This part of code is in my code multiple times. I'm calling it 5times only string "oznacenie_odpadu" is changing. Therefore I made function:
function select($data) {
$sql = "SELECT rozmer FROM zdroj_dat ORDER by id ASC";
if ($result = $conn->query($sql)) {
// fetch associative array
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row[$data].'" >'.$row[$data].'</option>';
}
}
}
Calling it with select("somevalue");
Syntax is ok because I didn't change anything but when I load the page the data from database are not retrieved.
You have a variable scope issue. $conn is not available inside of your function. You need to pass it as a parameter so ic an be used inside of your function.
function select($conn, $data) {
$sql = "SELECT rozmer FROM zdroj_dat ORDER by id ASC";
if ($result = $conn->query($sql)) {
// fetch associative array
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row[$data].'" >'.$row[$data].'</option>';
}
}
}
Call it:
select($conn, "somevalue");

While looping in mysqli prepared statement [duplicate]

This question already has answers here:
mysqli prepared statement with while loop
(2 answers)
Closed last year.
Is it possible to do something like we do in normal mysqli queries in prepared statements in while lopping.
For example
$sql = "SELECT * FROM users"*;
$query = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($query)){
echo $row['username'];
echo $row['name'];
}
In prepared statements, it goes like this
$fetch_comments = $friend_zone->prepare("SELECT item_poster, comment FROM status_comments WHERE status_id = ? and item_poster = ?");
$fetch_comments->bind_param("is", $status__id, $item_poster);
$fetch_comments->execute();
$fetch_comments->store_result();
$fetch_comments->bind_result($item_poster_fetched, $comment_fetched);
while($fetch_comments->fetch(){
echo $item_poster;
}
What i mean is i want to do the echo like so
echo $row['something'];
The solution i came up with now is to fetch them using bind result, then put them into an array inside the loop and then foo['bar']; or something of that sort.
Is there a better way?
Doesn't this work?
$fetch_comments = $friend_zone->prepare("SELECT item_poster, comment FROM status_comments WHERE status_id = ? and item_poster = ?");
$fetch_comments->bind_param("is", $status__id, $item_poster);
$fetch_comments->execute();
$result = $fetch_comments->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['something'];
}
You're almost there with your code. You just need to assign the value to $row within the while loop's condition check:
while( $row = $fetch_comments->fetch() ) {
echo $row['somefield'];
}
The data is now bound to the $item_poster_fetched variable from what I understand...
while($fetch_comments->fetch())
{
$item_poster_fetched['something'];
}

Recursive PHP function is not returning a result [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
Here is my function:
function loop($id) {
unset($result, $sql, $query);
$sql = " SELECT parent_id FROM page_entries WHERE id = '$id' ";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_assoc($query) or die(mysql_error());
if ($result['parent_id'] != 0) {
echo $result['parent_id'] . "... looping<br>";
loop($result['parent_id']);
} else {
echo $result['parent_id'] . "... done loop";
return $result['parent_id'];
}
}
echo loop('2');
I'm echoing the parent_id for testing. This is what is output to the browser:
1... looping
0... done loop
Where I'm not sure: the echo loop('2') doesn't echo anything from return $result['id'] if I comment out the echo lines in the function. I've tried testing by changing the return to return 'foo'; and still nothing.
How can I fix it?
At a glance, I think
loop($result['parent_id']);
should be
return loop($result['parent_id']);
otherwise your if branch is returning nothing.

Categories