in my last project I used foreach loop to assign to every mysqli result a variable, like $r->mydata, but I formatted my pc accidentally, so I lost my core file and I can't remember how exactly I did that. I remember that I did something like this
$result = $db->query("SELECT * FROM data");
if($result->num_rows){
while ($row = $result->fetch_object()) {
foreach ($row as $r){
$row[] = $r;
}
}
}
And I can access the result from outside the while loop like this:
<?php echo $r->mydata ?>
Can anyone edit my code so it will work like before?
it would be easier to use
$rows=$result->fetch_all(MYSQLI_ASSOC);
rather than looping through all the rows and building an array.
Maybe you don't remember how you did it, but if you did it once you should know at least which approach you followed to solve this, let help you to understand the code first:
$result = $db->query("SELECT * FROM data");
if($result->num_rows>0){
//iterating only if the table is not empty
while ($row = $result->fetch_object()) {
//Here you are iterating each row of the database
foreach ($row as $r){
//Here you are iterating each column as $r
//and (trying) adding it again to the $row array
$row[] = $r;
}
}
}
Why would you like to access to the $row outside the loop, if what you want to do is print each row, you can do it inside the loop:
$result = $db->query("SELECT * FROM data");
if($result->num_rows>0){
while ($row = $result->fetch_object()) {
foreach ($row as $r){
echo $r.'<br>';
}
}
}
If you do something like what follows, what part of the 'printed' data do you need? You may have been 'specializing' the result set by eliminating the rows to only use a single row...
$result = $db->query("SELECT * FROM data");
$r = new stdClass();
// Only loop if there is a result.
if ($result)
{
$r->myData = []; // You aren't exactly clear on 'myData'. In this instance, I am setting the rows inside of it.
while ($row = $result->fetch_object())
{
$r->myData[] = $row;
}
$result->close(); // Free result set
}
print_r($r->myData);
$records = array();
$result = $db->query("SELECT * FROM data");
if($result->num_rows){
while ($row = $result->fetch_object()) {
$records[] = $row;
foreach($records as $r);
}
}
and now you can access the result from any place in the page,example echo inside html h1:
<h1>My name is: <?php echo $r->name ?></h1>
Related
I am kinda new to SQL and I am having a problem. I am following the tutorial from Here to try to get data from my database into my android app.
I have it working, but it only gets one line. I know it should be possible to iterate through the database and echo out every line that matches the ID to JSON, but I do not know how. How would I do this?
My current code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM LATLON WHERE DeviceID='".$id."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"INDEX"=>$res['INDEX'],
"DeviceID"=>$res['DeviceID'],
"LAT"=>$res['LAT'],
"LON"=>$res['LON']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
?>
EDIT
I edited my code to this, but I am getting nothing. Still not quite understanding what is happening. Thanks for all the help!
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM LATLON WHERE DeviceID='".$id."'";
$r = mysqli_query($con,$sql);
while($row = $result->mysqli_fetch_array($r, MYSQLI_ASSOC)){
$array[] = $row;
}
echo json_encode($array);
mysqli_close($con);
}
?>
You can iterate through mysqli_fetch_array();
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$array[] = $row;
}
echo json_encode($array);
When you use the OO interface, the method names don't begin with mysqli_, that's only used for procedural calls. You also have no variable named $result, the result is in $r.
So it should be:
while ($row = $r->fetch_array(MYSQLI_ASSOC)) {
or:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
I need to print multiple database queries using json_encode(). I have this code below that outputs database records using json_encode. This works fine.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('SELECT username,firstname,lastname FROM user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
echo json_encode($data);
?>
I need to add another database query so that I can print them together using the same json_encode. Here is the database query that I want to add so that I can print them together using json_encode:
<?php
include('db.php');
$result = $db->prepare('SELECT price AS price1,goods AS product FROM provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
echo json_encode($data_pro);
?>
How can I accomplish this?
I think this might hit what you're looking for.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('select username,firstname,lastname from user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
$result = $db->prepare('select price as price1,goods as product from provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
// Combine both arrays in a new variable
$all_data['user'] = $data;
$all_data['pro'] = $data_pro;
echo json_encode($all_data);
I have 2 rows of data in my database and I am trying to fetch all rows
$query = mysqli_query($connection, "select username, email, is_admin from adminUsers");
$results = mysqli_fetch_assoc($query);
I have tried mysqli_fetch_assoc, mysqli_fetch_row, mysqli_fetch_array all of them just return 1 row of data.
mysqli_fetch_*() functions except mysqli_fetch_all(), if supported, fetch one row. Loop and fetch:
while($row = mysqli_fetch_assoc($query)) {
print_r($row);
//or you can echo $row['username'] etc...
//or store in an array to loop through later
$rows[] = $row;
}
If you use mysqlnd there is a mysqli_fetch_all() or use:
if(!function_exists('mysqli_fetch_all')) {
function mysqli_fetch_all($result, $resulttype=MYSQLI_BOTH) {
while($row = mysqli_fetch_array($result, $resulttype)) {
$rows[] =$row;
}
return $rows;
}
}
$results = mysqli_fetch_all($query);
But then you have to loop through all the returned rows anyway:
foreach($results as $row) {
print_r($row);
//or you can echo $row['username'] etc...
}
Switch to PDO to do it in a single go... Use PDOStatement::fetchAll
<?php
//.. Do the neccessary PDO connections...
$sth = $dbh->prepare("select username, email, is_admin from adminUsers");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
(or)
You need to loop through them... [MySQLi]
$query = mysqli_query($connection, "select username, email, is_admin from adminUsers");
$res = array();
while($results = mysqli_fetch_assoc($query))
{
$res[] = $results;
}
print_r($res);
Use while loop for fetching all lines:
while ($result = mysqli_fetch_assoc($query))
{
// Rest of your code. See an example below
echo $result['username'];
}
I am wondering if there a function in php that can allow me put all my selected data in an array .Currently i am using mysql_fetch_array and as i have read in the manual,that function won't fetch every record in the table.
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_array($result);
echo json_encode($array);
I would suggest the use of MySQLi or MySQL PDO for performance and security purposes, but to answer the question:
while($row = mysql_fetch_assoc($result)){
$json[] = $row;
}
echo json_encode($json);
If you switched to MySQLi you could do:
$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);
$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );
Loop through the results and place each one in an array
use mysqli_fetch_all() to get them all at one time
You could try:
$rows = array();
while($row = mysql_fetch_array($result)){
array_push($rows, $row);
}
echo json_encode($rows);
$name=array();
while($result=mysql_fetch_array($res)) {
$name[]=array('Id'=>$result['id']);
// here you want to fetch all
// records from table like this.
// then you should get the array
// from all rows into one array
}
This method is also very nice, you can try it.
try {
while ($row=mysqli_fetch_array($res)) {
array_push($row...);
}
} catch (Exception $e) {
print($e->getMessage());
}
you can call mysql_fetch_array() for no_of_row time
Here is my problem.
I need more than one row from the database, and i need the first row for certain task and then go through all the list again to create a record set.
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
$firstrow = //extract first row from database
//add display some field from it
while($row = mysql_fetch_assoc($result)) {
//display all of them
}
Now, how to extract just the first row?
Using mysql_fetch_assoc() not only fetches a row, it also moves the internal pointer of the result set to the next row. To reset the result resource to the first row, you need to use mysql_data_seek().
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
$firstrow = mysql_fetch_assoc($result);
// reset the result resource
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)) {
//display all of them
}
If you want to get all the rows from the first one again then try the following
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
if ( $row = mysql_fetch_assoc ($result){
$firstRow = $row;
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)) {
//display all of them
}
}
More about mysql_data_seek here: PHP: mysql_data_seek - Manual
you can use Object oriented style :
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
if ( $row = $result->fetch_assoc()){
$firstRow = $row;
mysql_data_seek($result, 0);
while( $row = $result->fetch_assoc()) {
//display all of them
}
}
Each time you call mysql_fetch_assoc($result), you get a row. So, instead of doing it repeatedly in a loop, just do it once:
$result = mysql_query("...");
if ($row = mysql_fetch_assoc($result)) {
$firstRow = $row;
while ($row = mysql_fetch_assoc($result)) {
// all the rest
}
}
Disclaimer: this could be prettier code, but you get the idea!