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."));
}
}
Related
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."));
}
}
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!!
I have been attempting to send my data from my app to my local server via php. I am able to parse my data through and serialised it into JSON and supposedly send it to the server like
this question will demonstrate. However when I test it on POSTMAN, the $array says that it is NULL and the $json says string(0)"". I am very confused as to why this is the case.
This is how my data is structured when parsed:
Optional([["record_id": 8EC9C1C9-7DD4-4343-B7CC-E4615FDDA150, "name": John ], ["record_id": 7EEA551D-9432-4737-99FB-6BFCF3A92D21, "name": Fred Smith]])
Below is my php file:
<?php
ini_set("display_errors", 1);
ini_set("html_errors", 1);
error_reporting(E_ALL);
$json = file_get_contents('php://input');
var_dump($json);
// convert to array
$array = json_decode($json, true);
var_dump($array);
$response = array();
//check if request is post
if($_SERVER['REQUEST_METHOD']=='POST'){
//assign values to variables
$recordID = $array['record_id'];
$name = $array['name'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($recordID, $name)){
$response['error']=false;
$response['message']='Record added successfully';
}else{
$response['error']=true;
$response['message']='Could not add record';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
and here is my DBOperations class:
<?php
class DbOperation
{
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createTeam($recordID, $name)
{
$stmt = $this->conn->prepare('INSERT INTO record(record_id, name) VALUES (?, ?)');
$stmt->bind_param("si", $recordID, $name);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}
I am really struggling to resolve this. Please let me know what is the best way to handle this.
I have been trying to build a register and login android app using php and mysql with android studio. It appears that the values are being entered to the databse but it is not giving a response back. Table name is harry and php file is:
<?php
define('DBUSER', 'id650955_gokulm100');
define('DBPASS', 'gokulm100');
define('DBHOST', 'localhost');
define('DBNAME', 'id650955_harry');
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
if (!$conn) {
die('error connecting to database');
}
echo 'you have created case';
if(isset($_POST["username"]) && isset($_POST["email"]) && isset($_POST["phone"]) && isset($_POST["password"]))
{
$username = $_POST["username"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$password = $_POST["password"];
$statement = mysqli_prepare($conn, "INSERT INTO harry (username, email, phone, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssis", $username, $email, $phone, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = 1;
echo json_encode($response);
}
else{
echo "not set";
}
?>
assuming that the data is inserted to the database you need to look at your output, it looks like you're sending json text via json_encode and in the same time echo a string "you have created case"
so your output will be a mix of simple characters and some json string. which probably send a parsing error to the callback in the android side of the code.
first you should add a header that indicates the you will be returning json code at the top of the file
header("Content-Type: application/json",true);
then change all your output to be json , any
echo "str";
should be
echo json_encode(array("message"=>"str"));
then see if you still don't get any message back.
I have this PHP Script that receives data from an android Application. What Security methods are used to ensure that this PHP script is secure?! like isset function?!
<?php
require ('config.php');
$connection=mysqli_connect($servername,$username,$password,$db);
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$movie_name=$obj['movie_name'];
mysqli_query($connection,"insert into movie (movie_id, movie_name) VALUES (NULL,'$movie_name');");
echo "inserted";
?>
Thanks in advance.
I've edited your example code to check for connection / json_decode failing, and to make use of prepared statements. You might consider doing some validation on the movie name e.g. is it shorter than the length of the database field for example. However, the prepared statements should stop any SQL injection:
<?php
require ('config.php');
$connection=mysqli_connect($servername,$username,$password,$db);
if (!$connection) {
// mysql connection failed - error
exit();
}
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
if( $obj == null ) {
// json decode failed
exit();
}
$stmt = $connection->prepare("INSERT INTO movie (movie_id, movie_name) VALUES (NULL, ?)");
$stmt->bind_param('s', $obj['movie_name']);
$stmt->execute();
$stmt->close();
echo "inserted";