i have a Persian data base that use collection utf8-general-ci but when i run below code i face with ???? instated of Persian words .
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "testinsta");
$result = $conn->query("SELECT m_1, m_2, m_3 FROM codecode");
mysqli_query($conn, "SET NAMES utf8");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["m_1"] . '",';
$outp .= '"City":"' . $rs["m_2"] . '",';
$outp .= '"Country":"'. $rs["m_3"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
mysql to json with php problem
You can do like this,
$conn = new mysqli("localhost", "root", "", "testinsta");
$conn->set_charset("utf8");
and remove below line,
mysqli_query($conn, "SET NAMES utf8");
and now check.
Here is brief details about Whether to use “SET NAMES”.
Related
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 4 years ago.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
include("global.php");
$conn = new mysqli(server, dbuser, dbpw, db);
$user = $_GET['user'];
//$customer = $_GET['customer'];
$querystring = "";
$querystring = "SELECT email, password, firstname, lastname from user ";
$result = $conn->query($querystring);
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"email":"' . $rs["email"] . '",';
$outp .= '"password":"' . $rs["password"] . '",';
$outp .= '"firstname":"' . $rs["firstname"] . '",';
$outp .= '"lastname":"' . $rs["lastname"]. '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
This is the PHP code in the database and need to use get method. the error shows undefined index : $user = $_GET['user']; when I run it shows this error. How to fix it?
You can fix this issue by add isset in $_GET['user'] and check its empty or not
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
include("global.php");
$conn = new mysqli(server, dbuser, dbpw, db);
if( isset($_GET['user']) && $_GET['user']!='' ){
$user = $_GET['user'];
}else{
$user='';
}
//$customer = $_GET['customer'];
$querystring = "";
$querystring = "SELECT email, password, firstname, lastname from user ";
$result = $conn->query($querystring);
enter code here
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"email":"' . $rs["email"] . '",';
$outp .= '"password":"' . $rs["password"] . '",';
$outp .= '"firstname":"' . $rs["firstname"] . '",';
$outp .= '"lastname":"' . $rs["lastname"]. '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
Another way is that you can add # in front of $_GET['user']
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
include("global.php");
$conn = new mysqli(server, dbuser, dbpw, db);
#$user = $_GET['user'];
//$customer = $_GET['customer'];
$querystring = "";
$querystring = "SELECT email, password, firstname, lastname from user ";
$result = $conn->query($querystring);
enter code here
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"email":"' . $rs["email"] . '",';
$outp .= '"password":"' . $rs["password"] . '",';
$outp .= '"firstname":"' . $rs["firstname"] . '",';
$outp .= '"lastname":"' . $rs["lastname"]. '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
I added the IF condition in below code you can check it. By adding this condition you are able to solve the undefine index issue
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
include("global.php");
$conn = new mysqli(server, dbuser, dbpw, db);
if(!isset($_GET['user']) && empty($_GET['user']))
return false;// this will send back if data or index is not found and also solve the undefine index problem
$user = $_GET['user'];
//$customer = $_GET['customer'];
$querystring = "";
$querystring = "SELECT email, password, firstname, lastname from user ";
$result = $conn->query($querystring);
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"email":"' . $rs["email"] . '",';
$outp .= '"password":"' . $rs["password"] . '",';
$outp .= '"firstname":"' . $rs["firstname"] . '",';
$outp .= '"lastname":"' . $rs["lastname"]. '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
There are many ways to check if an array's index is undefined. The example below uses two methods: isset and empty.
The call to isset returns true if the array has the specified key.
The call to empty will return true if the value for the specified index is "empty" (null, empty string, zero, empty array, etc...) or if the specified key does not exist.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
include("global.php");
$conn = new mysqli(server, dbuser, dbpw, db);
$user = isset($_GET['user'])&&!empty($_GET['user']) ? $_GET['user'] : NULL;
//$customer = $_GET['customer'];
$querystring = "";
$querystring = "SELECT email, password, firstname, lastname from user ";
$result = $conn->query($querystring);
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"email":"' . $rs["email"] . '",';
$outp .= '"password":"' . $rs["password"] . '",';
$outp .= '"firstname":"' . $rs["firstname"] . '",';
$outp .= '"lastname":"' . $rs["lastname"]. '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
Why a php file does not respond as json, but it responds to the connected file.
file respond
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include '../connect.php';
mysqli_set_charset($conn, "utf8");
$sql="SELECT confer_name, confer_begin_time, confer_end_time, confer_value, con_img FROM conference";
$outp = "";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0){
while($rs = $result->fetch_array(MYSQLI_ASSOC)){
if($outp != ""){$outp .=",";}
$outp .='{"cname":"' .$rs["confer_name"]. '",';
$outp .='"cbt":"' .$rs["confer_begin_time"] . '",';
$outp .='"cet":"' .$rs["confer_end_time"] . '",';
$outp .='"cvalue":"' .$rs["confer_value"] . '",';
$outp .='"cimg":"' .$rs["con_img"] . '"}';
}
$outp = '{"records":['.$outp.']}';
echo $outp;
}
?>//***
file connect This file is used to connect.
<?php
$servername = "localhost";
$username = "----";
$password = "----";
$database = "----";
$conn = new mysqli($servername,$username,$password,$database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
This result
modify your code as below
$outp = json_encode($outp);
The issue:
I'm converting some SQL tables into JSON format and I have some null values which aren't being presented in the format I would like. When there's a null value in my table, it turns into " " when converted to JSON, but I want it to just say null instead of double quotation marks.
The code:
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT firstname, middlename, lastname FROM nametable");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"firstname":"' . $rs["firstname"] . '",';
$outp .= '"middlename":"' . $rs["middlename"] . '",';
$outp .= '"lastname":"' . $rs["lastname"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
The JSON format that I am getting:
[
{"firstname":"John", "middlename": "Timothy", "lastname":"Doe"} ,
{"firstname":"Mary", "middlename":"", "lastname":"Jane"}
]
The JSON format that I want: (the different part is the null after middlename)
[
{"firstname":"John", "middlename":"Timothy", "lastname":"Doe"} ,
{"firstname":"Mary", "middlename": null, "lastname":"Jane"}
]
Edit: I don't want this: (because null will be treated as a string)
[
{"firstname":"John", "middlename":"Timothy", "lastname":"Doe"} ,
{"firstname":"Mary", "middlename":"null", "lastname":"Jane"}
]
What I have tried:
I tried editing my query to
SELECT firstname, middlename, lastname
FROM nametable
WHERE (nametable->>'middlename') is null
but it gets buggy and won't run.
I've also tried
SELECT firstname, middlename, lastname
FROM nametable
FOR JSON AUTO, INCLUDE_NULL_VALUES
but it also won't run.
Final edit: I played around with everyone's suggestions and I made it work with an if/else statement in the middle:
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT firstname, middlename, lastname FROM nametable");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"firstname":"' . $rs["firstname"] . '",';
if (is_null($rs['middlename']) == true)
$outp .= '"middlename":null,';
else
$outp .= '"middlename":"' . $rs["middlename"] . '",';
$outp .= '"lastname":"' . $rs["lastname"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
Convert your null field to string if you want to want JSON to print NULL instead of blank
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"firstname":"'. $rs["firstname"] == null ?"null":$rs["firstname"]. '",';
$outp .= '"middlename":"'. $rs["middlename"] == null ?"null":$rs["middlename"]. '",';
$outp .= '"lastname":"'. $rs["lastname"] == null ?"null":$rs["lastname"]. '"}';
}
Since having null inside the database causes problem, why not store "null" string instead, and when creating the JSON format, use conditional operator to select the real null .This is a sample, how your code suppose look like:
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"firstname":"' . $rs["firstname"] == "null" ? null : $rs["firstname"].'",';
$outp .= '"middlename":"' . $rs["middlename"] == "null" ? null : $rs["middlename"].'",';
$outp .= '"lastname":"' . $rs["lastname"] == "null" ? null : $rs["lastname"].'"}';
}
$outp .="]";
Here is an example with some dummy data
$db_results = array(
array('fname'=>'john', 'lname'=>'doe', 'property'=>''),
array('fname'=>'john', 'lname'=>'doe', 'property'=>''),
array('fname'=>'john', 'lname'=>'doe', 'property'=>NULL)
);
$output='';
$rowStr = '';
foreach($db_results as $i=>$row) {
$rowStr="{";
$rowStr.= '"fname":'.((is_null($row['fname']) || empty($row['fname'])) ? 'null' : '"'.$row['fname'].'"');
$rowStr.= ',"lname":'.((is_null($row['lname']) || empty($row['lname'])) ? 'null' : '"'.$row['lname'].'"');
$rowStr.= ',"property":'.((is_null($row['property']) || empty($row['property'])) ? 'null' : '"'.$row['property'].'"');
$rowStr.='}'; //add a comma here when a condition is met
$output.= $rowStr;
}
echo '['.$output.']';
Im trying to Fetch Data From a PHP Server Running MySQL. In my angular controller I do $http.get("dbconnection.php")
In my dbconnection.php I have this code which just Selects everything from the database and sends it back.
$conn = new mysqli......
$result = $conn->query("SELECT * FROM ...");
$outp = "";
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {
$outp .= ",";
}
$outp .= '{"id":"' . $rs["id"] . '",';
$outp .= '"name":"' . $rs["name"] . '",';
$outp .= '"price":"' . $rs["price"] . '"}';
$outp .= '"created":"' . $rs["created"] . '"}';
$outp .= '"img":"' . $rs["img"] . '"}';
}
$outp = '{"records":[' . $outp . ']}';
$conn->close();
echo $outp;
When I visit my site to see take a look at the Data under
Network Tab > XHR > dbconnection.php > Preview
I see the data but its weird formatted.
See picture of weird formatted json
I think thats the reason for why I get the
Unexpected token in JSON at position 43 ERROR
when I am trying to fetch the data.
To got well formatted JSON outputs, use json_encode function.
In your case :
$conn = new mysqli......
$result = $conn->query("SELECT * FROM ...");
$json = ["records" => []];
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$json["records"][] = $rs;
}
$conn->close();
echo json_encode($json);
i need to make a page which show all the items and when clicked bring me all the places where it is available.
i need to make this in mysql
app.controller('namesCtrl', function($scope) {
$scope.items = [
{name: 'item1', place: ['place1', 'place2']},
{name: 'item2', place: ['place2', 'place3']},
{name: 'item3', place: ['place1', 'place2', 'place3']},
{name: 'item4', place: ['place1']},
{name: 'item5', place: ['place1', 'place2']}
];
});
my php is
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "user", "pass", "table");
$result = $conn->query("SELECT * FROM `especialidades`");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"id":"' . $rs["id"] . '",';
$outp .= '"nombre_especialidad":"' . $rs["nombre_especialidad"] . '",';
$outp .= '"aguadilla":"' . $rs["aguadilla"] . '",';
$outp .= '"arecibo":"' . $rs["arecibo"] . '",';
$outp .= '"bayamon":"' . $rs["bayamon"] . '",';
$outp .= '"caguas":"' . $rs["caguas"] . '",';
$outp .= '"carolina":"' . $rs["carolina"] . '",';
$outp .= '"guayama":"' . $rs["guayama"] . '",';
$outp .= '"hato_rey":"' . $rs["hato_rey"] . '"}';
}
$outp ='{"especialidades":['.$outp.']}';
$conn->close();
echo($outp);
?>
im getting a lot of error.
how is the correct whay to make this in mysql and get it in json.
Your code should be like this
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "user", "pass", "table");
$result = $conn->query("SELECT id, nombre_especialidad,aguadilla,arecibo, bayamon,caguas,carolina,guayama,hato_rey FROM `especialidades`");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outArray["especialidades"][] = $rs;
}
$conn->close();
$outp = json_encode($outArray);
echo $outp;
?>
Hope this will help you!!