Loop mysqli_result - php

I can't seem to figure out how to loop through the rows in this object array. For example, how would I echo the value in each row?
$sql = "SELECT my_ids FROM manager WHERE is_live = 0";
$result = $db->query($sql);
When I print_r($result); I get
mysqli_result Object ( [current_field] => 0 [field_count] => 1
[lengths] => [num_rows] => 15 [type] => 0 )

Try to loop on $result with foreach loop:
<?php
foreach($result as $key => $val)
{
echo "key is=> ".$key." and Value is=>".$val;
}
Keys will be current_field field_count etc.

Make sure your are connected to the database. Example mysqli connection below.
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$database = "databasename";
$db = new mysqli($hostname, $username, $password, $database);
What you need is to fetch the data on your query and loop through on it. Like this
$sql = "SELECT my_ids FROM manager WHERE is_live = 0";
$result = $db->query($sql);
while ($manager_row = $result->fetch_assoc()) {
echo $manager_row ['my_ids'];
echo '<pre>'; print_r($manager_row);echo '</pre>';
}
You can also use fetch_all(). Like this
$sql = "SELECT my_ids FROM manager WHERE is_live = 0";
$result = $db->query($sql);
$all_results = $result->fetch_all();
foreach($all_resuls as $data){
print_r($data);
}

Are you looking for this?
while($row = mysqli_fetch_array($result)){
echo $row['my_ids'].'<br />';
}

Related

How do I store the results of the for loop as an array in the res variable?

I want to store the results of the for loop as an array in the variable
$res. How do I do it?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$sql1 = $con->query("SELECT (status) FROM `seita`");
$i = $sql1->num_rows;
echo $i;
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$res = mysqli_fetch_row($sql);
}
?>
The answer given by Rohit Mittal gave me array to string conversion error. What do I do next?
You can fetch all in one query with fetch_all() of mysqli
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$result = $con->query("SELECT status FROM `seita`")->fetch_all();
You could try to do it all in one line. Maybe something similar to this:
$res = $con->query("SELECT status
FROM `seita`
WHERE RollNo between 1 and (
SELECT count(status)
FROM `seita`
)
")->fetch_all();
You want to append to an array search google php array append which gives array_push($stack, "apple", "raspberry");
// Declare arrray
$res = []
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
// Append result to array
array_push($res, mysqli_fetch_row($sql));
}
You need to make an array and need to get only status value as below:
$res = [];
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$statusData = mysqli_fetch_row($sql);
$res[] = $statusData['status'];
}

Create nested JSON objects using PHP

I have the following MySQL table:
id desc qty
--------------------
10 abc 5
20 xyz 12
30 qwe 9
How can I use PHP/MySQL query to create the following JSON file?
{
"10":{"desc":"abc","qty":"5"},
"20":{"desc":"xyz","qty":"12"},
"30":{"desc":"qwe","qty":"9"}
}
Here is my attempt
$query="SELECT id,desc,qty FROM table";
$result = #mysql_query($query);
while ($row=mysql_fetch_object($result))
{
$data[]=$row;
}
echo json_encode($data);
The result is an array and I am not sure how to display it correctly
[
{"id":"10","desc":"abc","qty":"5"},
{"id":"20","desc":"xyz","qty":"15"},
{"id":"30","desc":"qwe","qty":"9"}
]
Any help is appreciated
There are many ways to achieve this.One of them is below. changes your database credentials and table name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM TableName";
$result = $conn->query($sql);
$results_array =array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results_array[$row['id']] = array(
'desc'=>$row['desc'],
'qty'=>$row['qty'],
);
}
} else {
echo "0 results";
}
$json_array = json_encode($results_array);
echo $json_array;
Results should be look alike
{
"1":{"desc":"abc","qty":"12"},
"2":{"desc":"xyz","qty":"54"}
}
Thanks for editing your question. You can change the structure of your results with another loop:
foreach($data as $d)
$r[$d->id] = ['desc' => $d->desc, 'qty' => $d->qty];
$data = $r;
right above:
echo json_encode($data);
or you could adjust your while loop to get the same result:
$data[$row->id] = ['desc' => $row->desc, 'qty' => $row->qty];
or you could use array column (again right above json_encode):
$data = array_column($data, null, 'id');
The last example produces a slightly different output, but you can still use it in many situations. If you can't the first two options are preferable.

mysqli_fetch_assoc returns ONLY the first element of the array

I'm working on a project, where the logged in user should be able to post notes on the homepage, and being logged in the certain user's notes should be printed above the new note form.
I've written a function for that, where the mysqli_query recognizes all the 6 entries I have, but the mysqli_fetch_assoc prints only the first note out of 6. What could I do wrong? Here is my code:
<?php
function find_notes_by_id($user_id) {
global $connection;
$safe_user_id = mysqli_real_escape_string($connection, $user_id);
$query = 'SELECT content ';
$query .= 'FROM notes ';
$query .= 'WHERE user_id = '.$safe_user_id;
$result = mysqli_query($connection, $query);
//mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 6 [type] => 0 )
confirm_query($result);
$row = mysqli_fetch_assoc($result);
//Array ( [content] => First! ) = it only shows the very first element
return $row;
}
?>
<?php
$notes_set = find_notes_by_id($userRow['id']);
foreach($notes_set as $note){
echo $note;
echo "<br />";
}
?>
You can get all results like so:
$arr = $result->fetch_all(MYSQLI_ASSOC);
Or use a while loop:
while($row = $result->fetch_assoc()){
echo $row['content'] . '<br />';
}
1.You need to iterate over your result-set object through while()
2.Save all your data to an array and then return that array to get all records
like below:-
<?php
function find_notes_by_id($user_id) {
global $connection;
$safe_user_id = mysqli_real_escape_string($connection, $user_id);
$query = "SELECT `content` FROM `notes` WHERE `user_id` = $safe_user_id";
$result = mysqli_query($connection, $query);
confirm_query($result);
$final_data = array(); // create an array
while($row = mysqli_fetch_assoc($result)){ // iterate over the result-set object to get all data
$final_data[] = $row; //assign value to the array
}
return $final_data; // return array
}
?>
Now:-
<?php
$notes_set = find_notes_by_id($userRow['id']);
print_r($notes_set) ; // print result to check array structure so that you can use it correctly in foreach
foreach($notes_set as $note){
echo $note['content'];
echo "<br />";
}
?>
Instead declaring $connection as global pass the $connection variable to the function which would be a efficient way and get the result as array
<?php
function find_notes_by_id($user_id,$connection) {
$safe_user_id = mysqli_real_escape_string($connection, $user_id);
$query = 'SELECT content ';
$query .= 'FROM notes ';
$query .= 'WHERE user_id = '.$safe_user_id;
$result = mysqli_query($connection, $query);
confirm_query($result);
$data = array(); // create an array
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
return $data;
}
?>
Now call the function like this
<?php
$notes_set = find_notes_by_id($userRow['id'],$connection);
foreach($notes_set as $note){
echo $note['content'];
}
?>
You have to iterate over.
Problem is with this code
$row = mysqli_fetch_assoc($result);
return $row;
Change that to
$x = array();
while( $row = mysqli_fetch_assoc($result))
{
$x[] = $row;
}
return $x;
Save data into an array. Use it through foreach or for loop.
$content = [];
while($row = mysqli_fetch_assoc($result)){
$content[] = $row['content'];
}
return $content;
Need to change the function like this
function find_notes_by_id($user_id) {
global $connection;
$safe_user_id = mysqli_real_escape_string($connection, $user_id);
$query = 'SELECT content ';
$query .= 'FROM notes ';
$query .= 'WHERE user_id = '.$safe_user_id;
$result = mysqli_query($connection, $query);
//mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 6 [type] => 0 )
confirm_query($result);
$row = array();
while($result1 = mysqli_fetch_assoc($result)){
//Array ( [content] => First! ) = it only shows the very first element
$row[] = $result1;
}
return $row;
}

How to display multiple array value in PHP?

I am having an trouble in displaying values in PHP.
Value pass through URL career.php?mode=1,2,3
Here is my code
$id = $_GET['mode']; // Id get from URL
//echo $id;
$query = "SELECT `job_title` FROM `job` WHERE `job_id` IN ($id)";
$res = mysqli_query($conn, $query);
foreach(($row = mysqli_fetch_array($res)) as $key1){
$key[] = $key1;
}
PHP Code:
<?php echo $key;?>
Hence it is in looping so it shows the last looped value. Is it possible to display the all values through loop.
Help me out guys!!
You have multiple options to output an array.
Echo and foreach
You c an loop through your array and echo each $key and $value
foreach ($keys as $key => $value) {
echo $key." : ".$value."<br />";
}
print_r and var_dump
This is mostly used in debugging.
print_r($keys);
var_dump($keys);
Imploding
You can implode your array to echo the concatted values.
// The first parameter is the devider or separator
echo implode('', $keys);
Is it possible to display more than one value from the column?
Yes, ofcourse. Look at the following example:
foreach ($keys as $value) {
echo $value['columnone'];
echo $value['columntwo'];
echo $value['columnthree'];
}
Resources
implode() - PHP Manual
print_r() - PHP Manual
var_dump() - PHP Manual
foreach - PHP Manual
As your code in open for sql injection you need to use bind and prepare statement . Use while loop to echo your data as
$ids[] = $_GET['mode']; // store it into array
$query = "SELECT `job_title` FROM `job` WHERE `job_id` IN (";
$query .= implode(',', array_fill(0, count($ids), '?'));// bind your param
$query .= ') ';
$stmt = $conn->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), $ids);//Call a callback with an array of parameters
$stmt->execute();
$stmt->bind_result($job_title);// bind result
while ($stmt->fetch()) {// use wlile loop here
printf("%s\n", $job_title);//echo result
}
You can do something like this:
$mysqli = new mysqli("server", "user", "password", "db");
$id = $_GET['mode'];
$query = "SELECT `job_title` FROM `job` WHERE `job_id` IN ($id)";
if($res = $mysqli->query($query)){
while($obj = $result->fetch_object()){
echo $obj->job_title;
}
}
$res->close();
Try this:
<?
$servername = "localhost";
$username = "yourUSERNAME";
$password = "yourPASS";
$dbname = "yourDBNAME";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
exit();}
$id = $_GET['mode']; // Id get from URL
//echo $id;
$query = "SELECT `job_title` FROM `job` WHERE `job_id`=".$id."";
$result = $conn->query($sql);
while($row=$result->fetch_assoc()){
//do something...
}
$conn ->close();
?>
tip: put your connection on another connection.php file.
like:
require('Connect.php');
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}

null value when i opened the php script in IE

I am trying to fetch the values from mysql table based on the certain values. below is my php script where i am getting json values from android and then parse it to array the passing array in to the select query.
So, when i open the script in IE i am getting values as null instead of []. What is wrong here.
php
<?php
$username = "xxxxx";
$password = "xxxxxx";
$host = "localhost";
$database="xxxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$JSON_received = $_POST["JSON"];
$obj = json_decode($JSON_received,true);
foreach ($obj['ilist'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
$im[] = $value;
}
$myquery = "SELECT * FROM Movies WHERE im_rat IN ('$im')";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
Can anyone help ?

Categories