I am fetching data from server and show in an array. Like this:
include 'config.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT * FROM author";
$result3 = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result3);
$response = array(
array('id' => $row['id'], 'name' => $row['name'], 'email' => $row['email'], 'picture_path' => $row['picture_path']),
);
it show me a single result but I want all the result through loop, help me fetch all data from database.
You have it almost all correct, you want to put the $row = mysqli_fetch_assoc($result3); with a loop:
include 'config.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT * FROM author";
$result3 = mysqli_query($conn, $sql);
while($row = $result3->fetch_assoc()) {
$response = array(
array('id' => $row['id'], 'name' => $row['name'], 'email' => $row['email'], 'picture_path' => $row['picture_path']),
);
}
But if you want to just echo the results out skip the array and just use:
echo "id: " . $row['id'] . " name: " . $row['name']. " email " . $row['email']. "picture_path" . $row['picture_path'];
while($row = mysqli_fetch_assoc($result3))
{
print_r($row);
}
it should be helpfull.
Just use a foreach to iterate through the $row array.
$response = array();
foreach ($row as $data)
{
$response[] = array(
'id' => $data['id'],
'name' => $data['name'],
'email' => $data['email'],
'picture_path' => $data['picture_path'])
);
}
Loop your array using foreach loop like this:
foreach($row as $res){
echo $res['id'];
echo $res['name'];
// continue like this....
}
It will echo your array from database.
Related
I am retrieving 5000 plus data in my MYSQL database. I takes 5-10 minutes to retrieve the data (it is only just local slower when over the network) is there a way to improve the speed without using a plugin?
$ContactID = $_GET["Contact"];
$sql = "SELECT * FROM tblContacts WHERE Coordinator = '$ContactID'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0){
while ($row = mysqli_fetch_array($result)) {
$supdate = date("Y-m-d h:i", strtotime($row['ServerUpdate']));
$mupdate = date("Y-m-d h:i", strtotime($row['MobileUpdate']));
$ar[] = array(
'ContactID' => $row['ContactID'],
'FileAs' => $row['FileAs'],
'FirstName' => $row['FirstName'],
'MiddleName' => $row['MiddleName'],
'LastName' => $row['LastName'],
'Position' => $row['Position'],
'Company' => $row['Company'],
'CompanyID' => $row['CompanyID'],
'ContactType' => $row['ContactType'],
'RetailerType' => $row['RetailerType'],
'PresStreet' => $row['PresStreet'],
'PresBarangay' => $row['PresBarangay'],
'PresDistrict' => $row['PresDistrict'],
'PresTown' => $row['PresTown'],
'PresProvince' => $row['PresProvince'],
'PresCountry' => $row['PresCountry'],
'Landmark' => $row['Landmark'],
'Telephone1' => $row['Telephone1'],
'Telephone2' => $row['Telephone2'],
'Mobile' => $row['Mobile'],
'Email' => $row['Email'],
'Employee' => $row['Employee'],
'Customer' => $row['Customer'],
'Coordinator' => $row['Coordinator'],
'ServerUpdate' => $supdate,
'MobileUpdate' => $mupdate
);
}
print json_encode($ar);
}
$ContactID = $_GET["Contact"];
$ar = array();
$sql = "SELECT ContactID,FileAs, FirstName ,MiddleName ,LastName ,Position ,Company ,CompanyID ,ContactType ,RetailerType ,PresStreet
,PresBarangay ,PresDistrict ,PresTown , PresProvince ,PresCountry ,Landmark ,Telephone1 , Telephone2 ,Mobile
,Email ,Employee ,Customer ,Coordinator FROM tblContacts WHERE Coordinator = '$ContactID'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0){
$rowCount = 0;
while ($row = mysqli_fetch_array($result)) {
$supdate = date("Y-m-d h:i", strtotime($row['ServerUpdate']));
$mupdate = date("Y-m-d h:i", strtotime($row['MobileUpdate']));
$ar[$rowCount] = $row;
$ar[$rowCount]['ServerUpdate'] = $supdate;
$ar[$rowCount]['ServerUpdate'] = $mupdate;
$rowCount++;
}
print json_encode($ar);
}
You must declare the variable of array first in the top.
You can directly call from mysql what data needed. Hope can help.
It could be like this way.
$contactID = $_GET["Contact"];
$sql = "SELECT * FROM tblContacts WHERE Coordinator = '$contactID'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$data = array();
while($row = mysqli_fetch_array($result)){
$row['supdate'] = date("Y-m-d h:i", strtotime($row['ServerUpdate']));
$row['supdate'] = date("Y-m-d h:i", strtotime($row['MobileUpdate']));
$data[] = $row;
}
print json_encode($data);
}
updated for multiple records
I making a script to monitorize data from some VPSs, which is being stored in a MySQL database.
$result = mysql_query("SELECT * FROM data");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array(
'id' => $row['id'],
'hostname' => $row['hostname'],
'loadavrg' => $row['load average']
);
}
I would like to separase data by hostnames so I can read it like the following example:
foreach($data['sitename.com'] as $d)
echo $d['loadavrg'];
I already tried with the following code (just for testing), but didn't work:
$result = mysql_query("SELECT * FROM data WHERE hostname='sitename.com'");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array(
'sitename.com' => array(
'id' => $row['id'],
'loadavrg' => $row['load average']
)
);
}
I'm just missing the right way and syntax to achieve it :X
Every element should be added as subarray of 'sitename.com':
while ($row = mysql_fetch_array($result)) {
$data['sitename.com'][] = array(
'id' => $row['id'],
'loadavrg' => $row['load average']
);
}
Try this,
while ($row = mysql_fetch_array($result)) {
$hostname = $row['hostname'];
$data[$hostname][] = array(
'id' => $row['id'],
'loadavrg' => $row['load average']
);
}
I am trying to extract data from mysql database into a datatable using ajax, and php.
The code for my response.php file is below:
<?php
$result = mysql_query("select * from orders");
while ($row = mysql_fetch_array($result)) {
$data = array(
array(
'Name' => $row['jobnumber'],
'Empid' => $row['ID'],
'Salary' => $row['product']
)
);
}
$results = array(
"sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data
);
/*while($row = $result->fetch_array(MYSQLI_ASSOC)){
$results["data"][] = $row ;
}*/
echo json_encode($results);
?>
Why is this only returning one result in my front end table?
http://orca.awaluminium.com/test.php
link above shows table.
You're replacing value of $data instead of pushing new rows in an array.
Change the following line.
$data = array(
array(
'Name'=>$row['jobnumber'],
'Empid'=>$row['ID'], 'Salary'=>$row['product']
)
);
To
$data[] = array(
'Name'=>$row['jobnumber'],
'Empid'=>$row['ID'], 'Salary'=>$row['product']
);
Also put $data=array(); before string while() looop.
You have to do foreach
while ($row = mysql_fetch_array($result)){
foreach($row as $a)
{$data[] = array(
array('Name'=>$a['jobnumber'], 'Empid'=>$a['ID'], 'Salary'=>$a['product']),
);
}
}
I've seen a few similar questions and tried the fixes and they are not working. Any help would be greatly appreciated.
I'm trying to return some data from the database as JSON.
Here is my code:
<?php
$db = "signup";
$servername = "localhost";
$username = "username";
$password = "password";
$fetch = ("SELECT * FROM bookings");
$return_arr = array();
$conn = new mysqli($servername, $username, $password, $db); // working
$query_result = mysqli_query($conn, $fetch);
mysqli_select_db("bookings",$db);
while ($row = mysqli_fetch_array($query_result, MYSQL_ASSOC)) {
$return_arr[] = array(
'TIMESLOT' => $row['TIMESLOT'],
'USERPIN' => $row['USERPIN'],
'PLAYERS' => $row['PLAYERS'],
'ACCEPTED' => $row['ACCEPTED'],
'EMAIL' => $row['EMAIL'],
'TOTAL BOOKINGS' => $row['TOTALBOOKINGS'],
'BOOKING ID' => $row['BOOKINGID'],
'LAST BOOKING' => $row['LASTBOOKING'],
'DATE' => $row['DATE']
);
}
$user = json_encode($return_arr);
echo "<pre>";
print_r($return_arr);
echo "</pre>";
mysqli_close($conn);
?>
Now I'm getting this information back from the database:
Array
(
[0] => Array
(
[TIMESLOT] => 12:00-14:00
[USERPIN] => 25225649
[PLAYERS] => 4
[ACCEPTED] => 0
[EMAIL] => email#address.com
[TOTAL BOOKINGS] => 0
[BOOKING ID] => 1
[LAST BOOKING] => 0000,00,00
[DATE] => 0000,00,00
)
)
I would change the while to this:
//...
$conn = new mysqli($servername, $username, $password, $db); // working
$query_result = mysqli_query($conn, "SELECT * FROM bookings");
//...
// Option 1 : Change MYSQL_ASSOC to MYSQLI_ASSOC
while ($row = mysqli_fetch_array($query_result, MYSQLI_ASSOC)) {
// Option 2 : Change to mysqli_fetch_assoc
// while ($row = mysqli_fetch_assoc($query_result)) {
// Debug
echo "<pre>";
print_r($row);
echo "</pre>";
$return_arr[] = array($row['BOOKINGID'],
$row['USERPIN'],
$row['TIMESLOT'],
$row['PLAYERS'],
$row['ACCEPTED'],
$row['EMAIL'],
$row['TOTALBOOKINGS'],
$row['LASTBOOKING'],
$row['DATE']
);
}
See that I added brackets to $return_arr, otherwise you'll be changing the value of the array and you'll get only the last one.
After that remove the "[0]" from the $return_arr[0]. This way you'll have the entire array encoded to json.
Try this code
$conn = new mysqli($servername, $username, $password, $db); // working
$sql = ""; // your query
$result = $conn->query($sql);
while($row = $result->fetch_array()) {
// Create results array
$rows[] = array(
'BOOKINGID' => $row['BOOKINGID'],
'USERPIN' => $row['USERPIN'],
// and go on....
);
}
mysqli_close($conn);
echo json_encode($rows[0]);
I would like to include a php function into the query loop which simply outputs all rows from a table.
This function would return another query counting the rows of individual users and would be encoded together with the first query.
The function works, if I echo the userId variable I get it right, but for a reason the count query returns null.
I could use some help, thanks!
<?php
include_once 'includes/db_connect.php';
$query = "SELECT * FROM UPLOADS";
//Creating resonse json array, with another array inside
$jsonResponse = array( "info" =>array() );
if($result = mysqli_query($mysqli, $query)) {
while($row = mysqli_fetch_assoc($result)){
$jsonRow = array(
'user' => $row['USER'],
'userId' => $row['USERID'],
'filename' => $row['FILENAME'],
'description' => $row['DESCRIPTION'],
'location' => $row['LOCATION'],
'address' => $row['ADDRESS'],
'likes' => $row['LIKES'],
'city' => $row['CITY'],
'lat' => $row['LAT'],
'lng' => $row['LNG'],
'countPost' => countUserPosts($row['USERID'])
);
//adding the $jsonRow array to the end of the "users" array as key/value
array_push($jsonResponse["info"], $jsonRow);
}
}
//encoding to json for the app
echo json_encode($jsonResponse);
function countUserPosts($userId){
$result = mysqli_query($mysqli, "SELECT count(*) FROM UPLOADS WHERE USERID = '$userId' ");
$row = mysqli_fetch_row($result);
$num = $row[0];
return $num;
}
?>
Try to inject the mysqli object inside your function paramater:
function countUserPosts($userId, $mysqli){
// ^ this one so it won't be out of scope.
$result = mysqli_query($mysqli, "SELECT count(*) FROM UPLOADS WHERE USERID = '$userId' ");
$row = mysqli_fetch_row($result);
$num = $row[0];
return $num;
}