im trying to insert data into a table from a json file but the rows gets 0. not the value from json
DB
JSON code:
{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
}]
}
$connection = mysql_connect("localhost", "***", "!*****!");
if (!$connection)
{
die('PHP Mysql database connection could not connect : ' . mysql_error());
}
$db_selected = mysql_select_db("*****", $connection);
$result=mysql_query("SELECT * FROM $tbl_name wHERE ad_IMEI=ad_IMEI ");
$i=0;
while($row=mysql_fetch_array($result)) {
$response[$i]['dr_DeviceID'] = $row['ad_IDDevice'];
$response[$i]['dr_UserLocalLat']= $row['user_location_lat'];
$response[$i]['dr_UserLocalLong']= $row['user_location_long'];
$data['posts'][$i] = $response[$i];
$i=$i+2;}
$json_string = json_encode($data);
$file = 'select.json';
file_put_contents($file, $json_string);
$jsondata = file_get_contents('select.json');
$obj = json_decode($jsondata, true);
$id = $obj['posts']['dr_DeviceID'];
$dr_UserLocalLat = $obj['posts']['dr_UserLocalLat'];
$dr_UserLocalLong = $obj['posts']['dr_UserLocalLong'];
$sqlj = "INSERT INTO $tbl_name1 (dr_DeviceID, dr_UserLocalLat, dr_UserLocalLong) VALUES('$dr_DeviceID', '$dr_UserLocalLat', '$dr_UserLocalLong')";
$result=mysql_query($sqlj,$connection);
The problem is that you're trying to access an array of objects as if it was a single one.
With this line here
$data['posts'][$i] = $response[$i];
you add an item to the $data['posts'] array. If your result had more than one row, the json example you've left above would be
{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
},
{
"dr_DeviceID": "324",
"dr_UserLocalLat": "39.7482572",
"dr_UserLocalLong": " -19.1847516"
}]
}
So, when you decode your json afterwards, you get an array of objects. To access every item in the array, you need some loop cycle. Otherwise, to get the first item from the json, you would need to do
$obj['posts'][0]['dr_UserLocalLat'], instead of $obj['posts']['dr_UserLocalLat'].
Related
I created an API for the Java desktop application because I want to get the data from an online database. The beginning was fine. But some parts were not shown as required. Below is how the data is in the database.
patient_id patient_name patient_nic patient_dob patient_note
PTT00001 Rebecca J Burns 988249675V 1998-12-17 Had previously taken medicine for...
PTT00002 Erica L Prom 926715648V 1992-06-21 To show up a second time for...
The PHP code I used to get this as JSON is as follows and it doesn't show any output(A blank page appeared)
PHP Code :
<?php
$con = mysqli_connect("localhost", "root", "", "on_dam_sys");
$response = array();
if($con){
$sql = "select * from patient";
$result = mysqli_query($con,$sql);
if($result){
header("Content-Type: JSON");
$i = 0;
while($row = mysqli_fetch_assoc($result)){
$response[$i]['patient_id'] = $row ['patient_id'];
$response[$i]['patient_name'] = $row ['patient_name'];
$response[$i]['patient_nic'] = $row ['patient_nic'];
$response[$i]['patient_dob'] = $row ['patient_dob'];
$response[$i]['patient_note'] = $row ['patient_note'];
$i++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
}
?>
But when the patient_name is removed using the same code, everything except it appears as below. What is the reason for that?
PHP code 2 :
<?php
$con = mysqli_connect("localhost", "root", "", "on_dam_sys");
$response = array();
if($con){
$sql = "select * from patient";
$result = mysqli_query($con,$sql);
if($result){
header("Content-Type: JSON");
$i = 0;
while($row = mysqli_fetch_assoc($result)){
$response[$i]['patient_id'] = $row ['patient_id'];
$response[$i]['patient_nic'] = $row ['patient_nic'];
$response[$i]['patient_dob'] = $row ['patient_dob'];
$response[$i]['patient_note'] = $row ['patient_note'];
$i++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
}
?>
Output for PHP code 02 :
[
{
"patient_id": "PTT00001",
"patient_nic": "988249675V",
"patient_dob": "1998-12-17",
"patient_note": "Had previously taken medicine for fever and still not cured. The body is lifeless."
},
{
"patient_id": "PTT00002",
"patient_nic": "926715648V",
"patient_dob": "1992-06-21",
"patient_note": "To show up a second time for heart disease. She is ready for surgery"
}
]
I also need to get the patient_name
Probably in one of the patient "name" there is some invalid char, in this case json_encode() simply return false, add JSON_THROW_ON_ERROR so the execution stop throwing an error.
echo json_encode($response, JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
Probably, adding also JSON_INVALID_UTF8_IGNORE will solve the problem.
Anyway, it is worth to find the offending row.
I am extremely confused on how to access this data, and get it into MySQL
I have this JSON Data:
{
"serial_number": "70-b3-d5-1a-00-be",
"dateTime": "2020-08-14 20:58",
"passReport": [
{
"id": 1,
"passList": [
{
"passType": 1,
"time": "20:58:38"
}
]
}
]
}
I can get serial_number & dateTime perfectly fine, however I cannot get passType & time into my database
Here is my code for injesting:
//read the json file contents
$jsondata = file_get_contents('php://input');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//mySQL creds & mySQL database & tables
$servername = "localhost";
$username = "my user";
$password = "my pass";
$dbname = "my db";
$serial_number = $data['serial_number'];
$dateTime = $data['dateTime'];
$id = $data['id'];
$passType = $data['passType'];
$time = $data['time'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Insert into Database Tables
$sql = "INSERT INTO mytable (serial_number, dateTime, passType, time)
VALUES('$serial_number', '$dateTime', '$passType', '$time')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I am pretty noobish at PHP, trying to learn! Appreciate any help here. I don't enough knowledge of accessing the data in the array.. Thanks in advance!
$data['passType']; makes no sense. It's clearly not on the same level of the object as serial number, for example.
You need to go down inside the hierarchy of the object. It's inside an array, and then another array.
Try
$data["passReport"][0]["passList"][0]['passType']
and
$data["passReport"][0]["passList"][0]['time']
instead.
<?php
//You can use var_dump to see the structure of decoded json, then you can access.
$jsondata = '{"serial_number":"70-b3-d5-1a-00-be","dateTime":"2020-08-14 20:58","passReport":[{"id":1,"passList":[{"passType":1,"time":"20:58:38"}]}]}';
$jdc = json_decode($jsondata,true);
var_dump($jdc);
var_dump($jdc['passReport'][0]['passList'][0]['passType']);
var_dump($jdc['passReport'][0]['passList'][0]['time']);
?>
I'm Parsing This json Array and I Want to Take type Object and Put That in New Column type2, and This is one Row of My json Rows,
I Get Invalid argument supplied for foreach() Because of New Line in json in Some Rows. How Can I Solve This?
This One is Not Okey
[{"id":"26","answer":[{"option":"4","text":"Hello
"}],"type":"3"}]
AndThis One is Okey
[{"id":"26","answer":[{"option":"4","text":"Hello"}],"type":"3"}]
And This is My Code:
<?php
$con=mysqli_connect("localhost","root","","array");
mysqli_set_charset($con,"utf8");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers`,us_id FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
if(!is_null($json)){
$jason_array = json_decode($json,true);
// type2
$type = array();
foreach ($jason_array as $data) {
if (array_key_exists('type', $data)) {
// Now we will only use it if it actually exists
$type[] = $data['type'];
}
}
// lets check first your $types variable has value or not?
if(!empty($type)) {
$types= implode(',',$type); /// implode yes if you got values
}
else {
$types = ''; //blank if not have any values
}
$sql2="update user_survey_start set type2='$types' where us_id=".$row[1];//run update sql
echo $sql2."<br>";
mysqli_query($con,$sql2);
}
}
}
mysqli_close($con);
?>
Replace your new line with \n before json decode:
$json = preg_replace('/\r|\n/','\n',trim($json));
$jason_array = json_decode($json,true);
The problem is invalid JSON format.
If your text content have multi lines, you should be use \n, not typing a enter.
[{"id":"26","answer":[{"option":"4","text":"Hello\n"}],"type":"3"}]
^^
I have an android application that sends some array of strings to php. php takes that array and inserts that data value individually into database. now when the data is inserted, each row data get an additional white space along with it.
how to eliminate it. i tried REPLACE with the string but when tried REPLACE, am unable to insert anything.
a white space is added when second row is entered.
here is the PHP code for entering data.
<?php
$response = array();
// check for required fields
if (isset($_POST['docname']) && isset($_POST['prods'])) {
$docname = $_POST['docname'];
$prods = $_POST['prods'];
$e = trim($prods, '[]');
$pr = preg_split("/[,]/", $e);
$img = "image/";
//$docs=array_unique($pr);
$count = count($pr);
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "root");
define("DB_DATABASE", "android_api");
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysqli_connect_error());
// selecting database
$db = mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
foreach ($pr as $val) {
$img = $img . $val . ".jpg";
// mysql inserting a new row
$result = mysqli_query($con,
"INSERT INTO product_entered(id, doc_name, product_name, image_path, count)
VALUES('$id','$docname','$val','$img','$count')"
);
}
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
when i display it using JSON, it looks like this..
{
"id": "15",
"doc_name": "Dr. XYZ",
"product_name": " PROTONIL-D",
"image_path": "image/image/ PROTONIL-D.jpg",
"count": "7"
},
{
"id": "14",
"doc_name": "Dr. XYZ",
"product_name": " PROATH_PLUS",
"image_path": "image/image/ PROATH_PLUS.jpg",
"count": "7"
},
a white space is inserted every time a row is inserted
i don't know how to solve this problem.
Have you tried to do a trim () in the loop?
foreach ($pr as $val) {
$val = trim($val);
$img = $img . $val . ".jpg";
$result = mysqli_query($con,
"INSERT INTO product_entered(id, doc_name, product_name, image_path, count)
VALUES('$id','$docname','$val','$img','$count')"
);
}
I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author