Passing JSON to PHP not working - php

I've been trying to get my python code to transfer SQL query data from client running python to web server running PHP, then input that data into a MySQL database.
The below is the python test code simulating a single row:
#!/usr/bin/python
import requests
import json
url = 'http://192.168.240.182/insert_from_json.php'
payload = {"device":"gabriel","data_type":"data","zone":1,"sample":5,"count":0,"time_stamp":"00:00"}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=dict(payload=json.dumps(payload)), headers=headers)
print response
The below is the PHP script on the server side:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload']
//$payload = '{"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}';
$payload_array = json_decode($payload_dump,true);
//get the data_payload details
$device = $payload_array['device'];
$type = $payload_array['data_type'];
$zone = $payload_array['zone'];
$sample = $payload_array['sample'];
$count = $payload_array['count'];
$time = $payload_array['time_stamp'];
$sql = "INSERT INTO data(device, data_type, zone, sample, count, time_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
If I comment out $payload_dump and instead use $payload and run the script the row is added correctly. But when I call the python script on the client I get a "response 200" but the record was not added. Something either my JSON string in python isn't formatted correctly or I am not passing the value correctly.
1) What is the syntax/procedure on the python code that would allow me to see what has actually been received by the PHP code. (i.e. convert the "$payload_dump" variable contents to a string and send back to the python script?
2) How do I resolve the above code?

Your first problem is using json headers which you shouldn't use since you aren't sending a raw json:
your data look like
{payload = {'key1': 'value1',
'key2': 'value2' }
}
and a raw json data should be in the form:
{'key1': 'value1',
'key2': 'value2'}
So you need to remove the headers from the request
response = requests.post(url, data=dict(payload=json.dumps(payload)))
Second you need to fix that missing semicolon
$payload_dump = $_POST['payload']
to
$payload_dump = $_POST['payload'];
Better solution
You can send the json data directly using requests
response = requests.post(url, json=payload)
then grab it in php with
$payload_array = json_decode(file_get_contents('php://input'), true);

Related

How do I insert simple rows of json data into a mysql table using PHP? [duplicate]

Hi I'm trying to insert the json array into my MySQL database. I'm passing the data form my iphone there i have converted the data into json format and I'm passing the data to my server using the url its not inserting into my server.
This is my json data.
[{"name":"0","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"13123123","phone":"sdfsdfdsfsd","city":"sdfsf","email":"13123123"}]
This is my Php code.
<?php
$json = file_get_contents('php://input');
$obj = json_decode($data,true);
//Database Connection
require_once 'db.php';
/* insert data into DB */
foreach($obj as $item) {
mysql_query("INSERT INTO `database name`.`table name` (name, phone, city, email)
VALUES ('".$item['name']."', '".$item['phone']."', '".$item['city']."', '".$item['email']."')");
}
//database connection close
mysql_close($con);
//}
?>
My database connection code.
<?php
//ENTER YOUR DATABASE CONNECTION INFO BELOW:
$hostname="localhost";
$database="dbname";
$username="username";
$password="password";
//DO NOT EDIT BELOW THIS LINE
$link = mysql_connect($hostname, $username, $password);
mysql_select_db($database) or die('Could not select database');
?>
Please tell where I'm doing wrong in the above code basically I'm not a php developer I'm mobile application developer so I'm using the php as a server side scripting please tell me how to resolve this problem.
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
I think you are passing the wrong variable. You should pass $json in json_decode as shown above.
You are missing JSON source file. Create a JSON file then assign it to var data:
<?php
require_once('dbconnect.php');
// reading json file
$json = file_get_contents('userdata.json');
//converting json object to php associative array
$data = json_decode($json, true);
// preparing statement for insert query
$st = mysqli_prepare($connection, 'INSERT INTO users(firstname, lastname, gender, username) VALUES (?, ?, ?, ?)');
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'ssss', $firstname, $lastname, $gender, $username);
// processing the array of objects
foreach ($data as $user) {
$firstname = $user['firstname'];
$lastname = $user['lastname'];
$gender = $user['firstname'];
$username = $user['username'];
// executing insert query
mysqli_stmt_execute($st);
}
There is no such variable as $data. Try
$obj = json_decode($json,true);
Rest looks fine. If the error still persists, enable error_reporting.
Its simple you can insert json datatype as below. reference link: click here for more details
insert into sgv values('c-106', 'admin','owner',false,'[{"test":"test"},
{"test":"test"}]',0,'pasds');
$string=mysql_real_escape_string($json);
header("Access-Control-Allow-Origin: http://localhost/rohit/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
//files needed to connect to database
include_once 'config/database.php';
include_once 'objects/main.php';
//get Database connection
$database = new Database();
$db = $database->getConnection();
//instantiate product object
$product = new Product($db);
//get posted data
$data = json_decode(file_get_contents("php://input"));
//set product property values
$product->b_nm = $data->Business_Name;
$product->b_pno = $data->Business_Phone;
$product->b_ads = $data->Business_Address;
$product->b_em = $data->Business_Email;
$product->b_typ = $data->Business_Type;
$product->b_ser = $data->Business_Service;
$name_exists = $product->nameExists();
if($name_exists){
echo json_encode(
array(
"success"=>"0",
"message" => "Duplicate Record Not Exists."
)
);
} else{
if($product->b_nm != null && $product->b_pno != null && $product->b_ads != null && $product->b_em != null && $product->b_typ != null && $product->b_ser != null){
if($product->create()){
//set response code
http_response_code(200);
//display message: Record Inserted
echo json_encode(array("success"=>"1","message"=>"Successfully Inserted"));
}
}
else{
//set response code
http_response_code(400);
//display message: unable to insert record
echo json_encode(array("success"=>"0","message"=>"Blank Record Not Exists."));
}
}

NuSOAP PHP web service and sending large string

again i am seeking for you help! I am new to NuSOAP, so please bear with me. I am trying to send multiple records, with multiple columns to my service, split this into records and writting them into my sql table.
For example, i have a batch that updates my variable like so (records are separated with ";", columns inside records are separated with "¤")
Name1¤Surname1¤Date1¤number1;Name2¤Surname2¤Date2¤number2;Name3¤Surname3¤Date3¤number3 ...
I have a simple function which accepts this variable. (1st of all i dont know if sending a string is optimal ... I read that i should be sending an xml document ...)
So if i declare a new variable inside my script and past the exact value that my program sets up, execute the script, everything works! Records are written in a table without any problem. I wrote up to 500 records. The problem is when i call my webservice ... In that case i get an error:
"SOAP Fault: error in msg parsing: XML error parsing SOAP payload on line 1: Invalid character:"
I think i am sending a to many chars in my variable ... Again i am new to NuSOAP and i am trying to figure this out based on an example i found online ...
When i was sending just text with only 1 delimeter, i was able to sent and write 500 records. The variable was setup like so:
TEST001;TEST002;TEST003; ...;TEST500
And the web service recieved the variable and wrote all 500 records to the table. Can someone please help me out or tell me the correct way of doing this?
Regards,
HEki
<?php
require 'lib/nusoap.php';
$server = new nusoap_server();
$server->configureWSDL("test"."urn:test");
$server->register(
"service",
array("variable_text"=>'xsd:string'),
array("return"=>"xsd:string")
);
function service($variable_text)
{
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "root";
$mysql_database = "service";
$today = date("Y-m-d");
$response='START';
// Connect to database server
$con = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
if (mysqli_connect_errno()) {
echo "ERROR: " . mysqli_connect_error();
}
$token = strtok($variable_text, ";");
while ($token !== false)
{
$data = explode('¤', $token);
$data0 = $data[0];
$data1 = $data[1];
$data2 = $data[2];
$data3 = (int)$data[3];
$strSQL = "INSERT INTO test (column1,column2,column3,column4) VALUES ('".$data0."','".$data1."','".$data2."', '".$data3."')";
mysqli_query($con,$strSQL);
$response='NEW';
$token = strtok(";");
}
// Close the database connection
mysqli_close($con);
return $response;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>

Retrieving JSON post data in php and inserting into mySQL database

I'm trying to send some Json formatted data via POST from a micropython controller to a PHP page and then into a mySQL database. The problem I am having is that the PHP code is not reading in the values from the Json data and therefore it is not being inserted into the database.
At the moment, it seems like the data is being successfully sent to the PHP page and in the right format. Here is the code below:
Python code sending the data to the php page:
data = '{"DeviceName": 1, "Humidity": %.2f, "Temperature": %.2f }'%(hum,temp)
headers = {'content-type': 'application/json'}
print(data)
res = urequests.post('http://192.168.1.187/insert.php', json=data, headers=headers)
print(res)
Here is the JSON string being sent:
{"DeviceName": 1, "Humidity": 36.88, "Temperature": 27.99 }
PHP code:
$server = "localhost";
$username = "admin";
$password = "passw";
$db = "test";
$dbCon = new mysqli($server, $username, $password, $db) or die("Unable to Connect");
$response = array();
$res=array();
$jsonRaw = file_get_contents('php://input');
$json = json_decode($jsonRaw);
if($json!=null){
$temperature = $json->Temperature;
$device = $json->DeviceName;
$sql = "insert into hostdata (HostID, DandT, Temp) values ('$device', now(), '$temperature')";
if(mysqli_query($dbCon, $sql)){
$svrResp["code"] = "1";
$svrResp["message"] = "Sucessfully Connected";
echo json_encode($response);
}else{
$svrResp["code"] = "2";
$svrResp["message"] = mysqli_error($dbCon);
echo json_encode($response);
}
}else{
echo "JSON data error";
}
mysqli_close($dbCon);
?>
This should insert the deviceName (is actually a number) and the temperature value into the sql statement and update the database. However, it is triggering the sql insert statement, just both the HostID and Temperature values are 0 when it is inserted. Am I missing something?
Any help would be appreciated!!

Send data from Python to PHP script

I want to do an HTTP GET request from the Python script to my server. The data I want to send is stored in a variable data.
I am using requests package of python to send it to my PHP page and I am getting the following error
import requests
data=850
r=requests.get("http://xxxxx.org/retrieve.php", params= str(data))
my retrieve.php file is
<?php
if (isset($_GET['data'])){
$data = $_GET['data'];
echo $data;
}
else{
echo "Data not received";
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$f=0;
$data= intval(data);
$sql="select max(ID) from moisture";
$res1 = mysqli_query($conn,$sql);
$row = mysqli_fetch_row($res1);
$ref = $row[0] + 1;
$sql1 = "INSERT INTO moisture VALUES ('$ref' , '$data')";
if (mysqli_query($conn, $sql1))
{
$f=1;
}
else {
$f=0;
}
mysqli_close($conn);
?>
I converted the data to string and then send it. On php script, I am getting the intval of the string but it is storing value '0' instead of '850'
My code is working for any static value that I am assigning to it. But it is not sending the data if I am receiving it from the sensor.
import serial
import requests
ser=serial.Serial('COM12',9600)
while True:
data=ser.readline()
r=requests.get("http://xxxxx.org/retrieve.php", params= data)

Can't Save URL Parameters in HTTP Get Request PHP

I'm working with Arduino and its GSM Shield. This is a hardware device that allows me to make an HTTP GET request to any IP address or web URL.
So we build a PHP script that reads URL parameters, and submits that data to the database. It will be saving our Arduino data when it pings our server.
Right now, when I visit the URL with the parameters in my browser, it works great. Everything saves and can be accessed via DB. But when the Arduino makes the request or I ping the URL with cURL, the record doesn't get saved.
The response I get shows that it is loading the page and spitting back the expected HTML. Why is my PHP not reading these URL parameters and saving them?
I've looked into sessions, etc no luck.
Thanks in advance!!
EDIT:::
handle_data.php (parses parameters, saves them to DB)
<?php
// Setup our DB login info
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "arduino";
if (!empty($_GET['lat']) && !empty($_GET['lon'])) {
function getParameter($par, $default = null){
if (isset($_GET[$par]) && strlen($_GET[$par])) return $_GET[$par];
elseif (isset($_POST[$par]) && strlen($_POST[$par]))
return $_POST[$par];
else return $default;
}
$lat = getParameter("lat");
$lon = getParameter("lon");
$person = $lat.",".$lon.",".$time.",".$sat.",".$speed.",".$course."\n";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO gps_data (latitude, longitude)
VALUES (".$lat.", ".$lon.")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
// close connection
$conn->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else {
};
?>
Here's the Arduino Code:
if(started) {
//GPRS attach, put in order APN, username and password.
//If no needed auth let them blank.
if (inet.attachGPRS("internet.wind", "", ""))
Serial.println("status=ATTACHED");
else Serial.println("status=ERROR");
delay(1000);
//Read IP address.
gsm.SimpleWriteln("AT+CIFSR");
delay(5000);
//Read until serial buffer is empty.
gsm.WhileSimpleRead();
//TCP Client GET, send a GET request to the server and
//save the reply.
numdata=inet.httpGET("http://cd5d6640.ngrok.io", 80, "/handle_data.php?lat=44.87654&lon=-88.77373", msg, 50);
//Print the results.
Serial.println("\nNumber of data received:");
Serial.println(numdata);
Serial.println("\nData received:");
Serial.println(msg);
}
Note - We're developing on localhost with MAMP, using ngrok to tunnel to localhost:8888. It works fine when you visit the ngrok url in the browser, but not when we hit it with a request. The url included is irrelevant and not active.

Categories