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]);
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 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.
I'm storing a JSON array in a mysql TEXT field using PDO. (encoded with json_encode())
Once I get the data, if I do json_decode the result is NULL.
It seems that PDO is replacing every " with ".
I have already use PDO and JSON together multiple times, but this is the first time I got this problem so I don't understand what's happening.
I'm on PHP 5.4.4
Also, the JSON is sent with AJAX for your information
Thanks if you can help.
Example of JSON in the table :
{"type_voie":"BD","indice_repetition":"T","num_voie":"121","nom_voie":"NOM_RUE","infos_voie":"NOM_RUE2","distribution_speciale":"BP789","cp":"34000","ville":"MONTPELLIER","bureau_distributeur":""}
What i really see with var_dump :
{"type_voie":"BD","indice_repetition":"T","num_voie":"121","nom_voie":"NOM_RUE","infos_voie":"NOM_RUE2","distribution_speciale":"BP789","cp":"34000","ville":"MONTPELLIER","bureau_distributeur":""}
This is inserted with a prepared query
Code for retrieve DATA :
$formDataSQL = '
SELECT * FROM '.$this->prefix.'
WHERE formalite_id = '.$this->proc_id.'
';
$formDataReq = self::$db->prepare($formDataSQL);
$formDataReq->execute();
$formData = $formDataReq->fetch(PDO::FETCH_ASSOC);
Then on the JSON field :
$addrData = json_decode(str_replace('"', '"', $champ['value']), true); // WORKING BUT NOT MAINTAINABLE
$addrData = json_decode($champ['value'], true); // NOT WORKING => NULL + JSON ERROR = JSON_ERROR_SYNTAX
Here is a simplified example of my insert code :
foreach($saveData['personne_physique'] as $field => $value){
if(is_array($value)) $value = json_encode($value);
$param = ':'.$field;
$fields .= $field.'='.$param.', ';
$values[$param] = $value;
}
$fields = trim($fields, ', ');
$persPhysSQL = "UPDATE personne_physique SET $fields WHERE personne_id = ".$this->id;
$persPhysReq = self::$db->prepare($persPhysSQL);
$persPhysReq->execute($values);
Here is how I'm connecting :
$host = 'mysql:dbname='.BDD_NAME.';host='.BDD_HOST.';charset=utf8';
$user = BDD_USER;
$pass = BDD_PASS;
$db = new PDO($host, $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") );
This is really strange :(
Here is my example script based on your data example:
<?php
try {
$Connection = new PDO('mysql:host=localhost;dbname=testing', USER, PASS);
$Connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'Unable to connect to database' . "\n";
}
$id = $argv[1];
try {
$data = $Connection->prepare('SELECT * FROM `stackoverflow_26399231` WHERE ID = :id');
$data->bindParam(':id', $id, PDO::PARAM_INT);
$data->execute();
while($row = $data->fetch(PDO::FETCH_OBJ)){
print_r($row);
print_r(json_decode($row->data));
}
$Connection = null;
}catch(PDOException $e){
echo 'Error executing query: ' . $e->getMessage() . "\n";
}
?>
The database table looks like this:
*************************** 1. row ***************************
id: 1
data: {"type_voie":"BD","indice_repetition":"T","num_voie":"121","nom_voie":"NOM_RUE","infos_voie":"NOM_RUE2","distribution_speciale":"BP789","cp":"34000","ville":"MONTPELLIER","bureau_distributeur":""}
When you run the script in the CLI, you get this back:
stdClass Object (
[id] => 1
[data] => {"type_voie":"BD","indice_repetition":"T","num_voie":"121","nom_voie":"NOM_RUE","infos_voie":"NOM_RUE2","distribution_speciale":"BP789","cp":"34000","ville":"MONTPELLIER","bureau_distributeur":""}
)
stdClass Object (
[type_voie] => BD
[indice_repetition] => T
[num_voie] => 121
[nom_voie] => NOM_RUE
[infos_voie] => NOM_RUE2
[distribution_speciale] => BP789
[cp] => 34000
[ville] => MONTPELLIER
[bureau_distributeur] =>
)
How does my script differ to yours? I'm not able to reproduce the issue.
UPDATE:
My update script following your example:
try {
$Connection = new PDO('mysql:host=localhost;dbname=testing', USER, PASS);
$Connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'Unable to connect to database' . "\n";
}
$id = $argv[1];
$ary = array(
'foo' => 'bar',
'bar' => 'foo',
'a' => 'b',
'c' => 'd',
'e' => 'f'
);
try {
$fields = 'data=:data';
$values = array('data' => json_encode($ary));
$update = $Connection->prepare("UPDATE `stackoverflow_26399231` SET $fields WHERE ID = $id");
$update->execute($values);
$Connection = null;
}catch(PDOException $e){
echo 'Error executing query: ' . $e->getMessage() . "\n";
}
Using the same script to receive as above but changing from PDO::FETCH_OBJ to PDO::FETCH_ASSOC as that's what you're using, I get this output:
Array
(
[id] => 1
[data] => {"foo":"bar","bar":"foo","a":"b","c":"d","e":"f"}
)
stdClass Object
(
[foo] => bar
[bar] => foo
[a] => b
[c] => d
[e] => f
)
So I can still not reproduce the issue you're having. There must be something different between the two scripts.
I want to get all locations in table travel_location in mysql. This is my code
$select = $this->_db_table->select()->from(travel_location, array('*'));
$result = $this->_db_table->fetchAll($select);
if(count($result) == 0) {
throw new Exception('not found',404);
}
while ($row1 = mysql_fetch_array($result)){
$user_object = new Api_Model_User($row1);
$count = 1;
$json = array($json[$count] = array(
'travel_location_id' => $user_object->travel_location_id,
'city_id' => $user_object->city_id,
'user_id' => $user_object->user_id,
'location_name' => $user_object->location_name,
'description' => $user_object->description,
'longitude' => $user_object->longitude,
'latitude' => $user_object->latitude,
'created_time' => $user_object->created_time,
'updated_time' => $user_object->updated_time));
$count++;
}
It doesn't work. I print $row1 = mysql_fetch_array($result) and it returns false, so I think it's wrong because of this line. How can I fix it?
If you use fetchAll from Zend_Db_Table you get a Zend_Db_Table_Rowset as result.
Try this:
foreach ($result as $row) {
// $row should be a Zend_Db_Table_Row object
// you can cast to array
$rowArray = $row->toArray();
$user_object = new Api_Model_User($rowArray);
}
Read more about here and here
I am having trouble at creating a specific array.
What i want is to pull the info for my members (from mysql database) and then store them to an array.
The array should be like this:
$members = array(
'John' => array('avatar' => '/images/avatar/ji.jpg', 'country' => 'uk.'),
'Nick' => array('avatar' => '/images/avatar/nick.jpg', 'country' => 'italy.'),
);
etc..
so i pull the name,avatar url and country from the db and then i store them in to the previous array.
My question is, how could i create this array?
Thanks in advance!
About creating an array at php.
Something like this should work:
$members = array();
$q = mysql_query("SELECT name , avatar, country from table");
while($row = mysql_fetch_assoc($q)){
$array = array("avatar" => $row['avatar'] , "country" => $row['country']);
$members[$row['name']] = $array;
}
Using PDO:
$members = array();
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$sql = "SELECT name, avatar, country FROM members";
foreach ($conn->query($sql) as $row) {
$temp = array('avatar' => $row['avatar'], 'country' => $row['country']);
$members[$row['name']] = $temp;
}