JSON received as quote (with "" mark) - php

I keep receiving my JSON from my web service inside quotation marks, like this:
"[{"id":"1","nombre":"Cecilia","correo":"csoto#ts.edu.mx","telefono":"5529964"},{"id":"2","nombre":"Romero","correo":"","telefono":"5435432"},{"id":"3","nombre":"nick","correo":"carlos#mail.com","telefono":"12345"}]"
Notice the "" before the brackets and I don't know why.
I'm using jacwright's restServer (https://github.com/jacwright/RestServer) with this function:
public function getUsers()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "estudiantes";
// Create connection
$array = array();
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, nombre, correo, telefono FROM estudiante";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$res = array("id" => $row["id"], "nombre" => $row["nombre"], "telefono" => $row["telefono"], "correo" => $row["correo"]);
array_push($array, $res);
//echo "id: " . $row["id"]. " - Name: " . $row["nombre"]. " " . $row["correo"]. "<br>";
}
}
$conn->close();
return json_encode($array) ;
}
Can somebody insight me why it keeps adding these quotation marks?

Just a quick example simulating your case, using echo to return JSON encoded array:
JS:
$.get('json.php', function(data) {
console.log(data);
if (data) {
//Check the console, everything is working like charm
newData = $.parseJSON(data);
console.log(data);
console.log('--------------' + 'Elements count:' + newData.length);
console.log('--------------' + newData);
}
});
json.php:
<?php
$myArr = array(
array("id"=>"1","nombre"=>"Cecilia","correo"=>"csoto#ts.edu.mx","telefono"=>"5529964"),
array("id"=>"2","nombre"=>"Romero","correo"=>"","telefono"=>"5435432"),
array("id"=>"3","nombre"=>"nick","correo"=>"carlos#mail.com","telefono"=>"12345")
);
$jsonData = json_encode($myArr);
echo $jsonData;
?>
Same above code using return $jsonData; instead of echo $jsonData; in json.php it gives me the following in the console:
emptiness for data
console error:
ReferenceError: newData is not defined

The reason of getting the quotes in the returned string is because the server (https://github.com/jacwright/RestServer) is doing json_encode itself. So when you return the data from your function getUsers and you have used json_encode it is converted to a json string and when RestServer returns it to you it sees it only as a string therefore adding quotes around it.
If you look at the TestController you will see that it returns an object $user not json_encode($user) and RestServer in it's sendData function actually uses the json_encode function.
So your code needs to be:
public function getUsers()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "estudiantes";
// Create connection
$array = array();
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, nombre, correo, telefono FROM estudiante";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$res = array("id" => $row["id"], "nombre" => $row["nombre"], "telefono" => $row["telefono"], "correo" => $row["correo"]);
array_push($array, $res);
//echo "id: " . $row["id"]. " - Name: " . $row["nombre"]. " " . $row["correo"]. "<br>";
}
}
$conn->close();
return $array;
}
Also check out the function sendData in https://github.com/jacwright/RestServer/blob/master/source/Jacwright/RestServer/RestServer.php#L414 on line 414.

Related

php returns empty GET array when trying to fetch MySQL data

I am trying to make a php REST API for my mobile backend to interact with a MySQL database. I have written out the following code to try and retrieve data from a MySQL query:
<?php include "FILE WITH DB_INFO"; ?>
<html>
<body>
<h1>Testing page</h1>
<?php
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL" . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
if (strlen($username_query)) {
doesUsernameExist($connection, $username_query);
}
doesUsernameExist($connection, $username_query);
$username_query = $_GET['usernameToQuery'];
echo($_GET['usernameToQuery']);
function doesUsernameExist($connection, $username) {
$u = mysqli_real_escape_string($connection, $username);
$query = "SELECT username from users WHERE username = ('$u');";
if (!mysqli_query($connection, $query)) {
$response = array("success" => false, "message" => mysqli_error($connection), "sqlerrno" => mysqli_errno($connection), "sqlstate" => mysqli_sqlstate($connection));
echo json_encode($response);
} else {
$sth = mysqli_query($connection, $query);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
$response = array("success" => true);
echo json_encode($rows);
}
}
?>
This is what the actual request looks like: http://my_ec2_instance/DoesUsernameExist.php?usernameToQuery=lmao.
This is sent through POSTMAN.
Because the MySQL database that I am using contains usernames with the value lmao, the php function should return an array that is not empty. But the json_encode($rows); line returns an empty array []. What am I doing wrong.
It seems you call doUsernameExiste() and just before strlen with a variable $username_query. But you define $username_query only after.
You should first do your affectation. Put this after your line with the mysqli_select_db
$username_query = $_GET['usernameToQuery'];

PHP SQL request returns "???" instead of cyrillic

I know this question has already been asked here, but there is still no solution for me ...
I have $http.post request to the server. It should return me the JSON file.
$http.post(getCountry, angular.toJson({country: true})).then(function (data) {
$scope.countries = data.data;
console.log( 'Success', $scope.countries);
}, function (err) {
console.log('err');
});
The php code, which should send request to MySQL is as fallows:
$connection = mysqli_connect($server, $login, $password, $db) or die("Connection error" . mysqli_error($connection));
if ($country == 1) {
$sql = "SELECT name_ru, id FROM net_country ORDER BY name_ru";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
}
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
This one returns JSON with "?????" instead of the "name_ru"
When I change "name_ru" to "name_en" - everything is ok.
I have no idea how to fix it.
UTF-8 charset is everywhere

PHP > Invalid Argument supplied for foreach()

In short, I am trying to figure out what is wrong with my foreach statement. I have been trying to work on finding the error for over a day know and I'm running out of time. This program is supposed to parse a json array and post it up to a mysqli database.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$a = print_r(var_dump($GLOBALS),1);
echo htmlspecialchars($a);
$servername = "#";
$username = "#";
$password = "#";
$dbname = "#";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
echo "Connection Successful : ";
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Read JSON file
$jsondata = file_get_contents('scripts/AUDIT_DIR/report.json');
echo "JSON File Read : ";
// Convert and Loop
$item = json_decode($jsondata, true);
echo "JSON File Decoded : ";
foreach($item as $arr)
{
$id = $arr["id"];
$hostname = $arr["hostname"];
$ip = $arr["ip"];
$package = $arr["package"];
$publisher = $arr["publisher"];
$origin = $arr["origin"];
$version = $arr["version"];
$size = $arr["size"];
$sql = "INSERT INTO testtable(id, hostname, ip, package, publisher, origin, version, size)
VALUES ('10', '$hostname', '$ip', '$package', '$publisher', '$origin', '$version', '$size')";
if (mysqli_query($conn, $sql))
{
echo "New record created successfully : ";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
You likely have an invalid return from your json_decode() you can check this with a var_dump($item); after your json_decode()
In php json_decode() will return NULL if the json cannot be decoded or if the encoded data is deeper than the recursion limit. http://php.net/manual/en/function.json-decode.php
You need to properly guard for such a case that $item === null and not assume you will always get a valid return for your foreach() params.
Example showing your error happens when $item = null
https://3v4l.org/oNr8P

Warning: mysqli_query(): Couldn't fetch mysqli in my code

I know this question has been asked many times , I tried lot of other answers but it didn't work for me
Here is my class
<?php
class saveexceltodb
{
var $inputFileName;
var $tableName;
var $conn;
var $allDataInSheet;
var $arrayCount;
/**
* Create a new PHPExcel with one Worksheet
*/
public function __construct($table=0)
{
$this->initiatedb();
}
private function initiatedb(){
//var_dump($allDataInSheet);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyx";
// Create connection
$this->conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
public function updateIntermidiate(){
$allocationeventwise=array();
mysqli_query($this->conn,"DELETE FROM `allocationeventwise` WHERE 1");
$sql = "INSERT INTO `allocationeventwise` (`empid`, `event1`, `event2`, `event3`, `event4`, `event5` `event6`, `event7`) VALUES ";
$result = mysqli_query($this->conn, "SELECT usdeal.empid , usdeal.event1 , usdeal.event2, usdeal.event3, usdeal.event4, usdeal.event5, usdeal.event6, usdeal.event7 , salary.salary from usdeal INNER JOIN salary ON usdeal.empid = salary.empid where usdeal.allocated=0");
$i=0;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$i++;
$totaleventDays = $row["event1"]+$row["event2"]+$row["event3"]+$row["event4"]+$row["event5"]+$row["event6"]+$row["event7"];
$allocationeventwise[$row["empid"]]['event1']=($row['salary']/$totaleventDays)*$row["event1"];
$allocationeventwise[$row["empid"]]['event2']=($row['salary']/$totaleventDays)*$row["event2"];
$allocationeventwise[$row["empid"]]['event3']=($row['salary']/$totaleventDays)*$row["event3"];
$allocationeventwise[$row["empid"]]['event4']=($row['salary']/$totaleventDays)*$row["event4"];
$allocationeventwise[$row["empid"]]['event5']=($row['salary']/$totaleventDays)*$row["event5"];
$allocationeventwise[$row["empid"]]['event6']=($row['salary']/$totaleventDays)*$row["event6"];
$allocationeventwise[$row["empid"]]['event7']=($row['salary']/$totaleventDays)*$row["event7"];
$sql .='("'.$row["empid"].'",
'.$allocationeventwise[$row["empid"]]["event1"].',
'.$allocationeventwise[$row["empid"]]["event2"].',
'.$allocationeventwise[$row["empid"]]["event3"].',
'.$allocationeventwise[$row["empid"]]["event4"].',
'.$allocationeventwise[$row["empid"]]["event5"].',
'.$allocationeventwise[$row["empid"]]["event6"].',
'.$allocationeventwise[$row["empid"]]["event7"].',)';
if($i<mysqli_num_rows($result))
$sql .=",";
else
$sql .=";";
}
echo $sql;
if (mysqli_query($this->conn, $sql)) {
echo "New record created successfully<br/>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($this->conn);
}
} else {
echo "0 results";
}
}
}
When I use it like this
include('saveexceltodb.php');
$obj = new saveexceltodb(0);
$obj->updateIntermidiate();
I get following error .
Warning: mysqli_query(): Couldn't fetch mysqli in C:\xampp\htdocs\import-excel\saveexceltodb.php
You should follow below steps
Check database connection
Check query syntax
You have to pass connection object in mysqli_query function in you case it is ' $this->conn '
Hope, It may help you.

How to write php returns json format according to the key?

I use XAMPP to create local networks and write php file to return the data in the database as json. This is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "landslide";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function myexample {
$mysqli = "SELECT id, temp, acc, moisture, battery, time FROM devices";
$result = $conn->query($mysqli);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
$response["main"] =array();
$response["parameters"]= array();
$main = array();
$main["id"]=$row["id"];
array_push($response["main"],$main);
$parameter = array();
$parameter["temp"] = $row["temp"];
$parameter["acc"] = $row["acc"];
$parameter["moisture"] = $row["moisture"];
$parameter["battery"] = $row["battery"];
$parameter["time"] = $row["time"];
array_push($response["parameters"],$parameter);
}
// echoing JSON response
$result_response = echo json_encode($response);
return $result_response;
}
} // end of my example function
?>
now when you call this function you will get json_encode format
now parse it by using
$res = JSON.parse($result_response);
now
$moisture = $res['moisture'];
My local link: http://127.0.0.1/landslide/currentdata.php .
Now, I want to write one php file returns json format according to the "key"(here i want key is id). As of Openweather api address below, key is cities (example London). http://api.openweathermap.org/data/2.5/weather?q=London,uk
So, how to i return json format by php according to key? Please help me! (My expression was not good, sorry about that)
when you are returning the json_encode($response);
You need to parse it to get in like an object and access it you can achieive it like in one variable.
$result = JSON.parse($response);
and access this $result array like if you want to access moisture
then $moisture = $result['moisture']; like so on...

Categories