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.
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 am trying to send data (temperature, humidity and time) from postman through API link for testing my code. I upload my php files in hostinger.com and every time I am trying to send data through postman it gives me OK and no errors but the data not showing in my phpmyadmin database table!
my insert.php code:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
//Creating Array for JSON response
$response = array();
// Check if we got the field from the user
if (isset($_GET['temp']) && isset($_GET['hum']) && isset($_GET['time'])) {
$temp = $_GET['temp'];
$hum = $_GET['hum'];
$time = $_GET['time'];
// Include data base connect class
$filepath = realpath (dirname(__FILE__));
require_once($filepath."/db_connect.php");
// Connecting to database
$dbo = new DB_CONNECT();
// Fire SQL query to insert data in weather
$result = "INSERT INTO 'climate'('temp', 'hum', 'time') VALUES('$temp', '$hum', '$time')";
// Check for succesfull execution of query
if ($result) {
// successfully inserted
$response["success"] = 1;
$response["message"] = "climate successfully created.";
// Show JSON response
echo json_encode($response);
} else {
// Failed to insert data in database
$response["success"] = 0;
$response["message"] = "Something has been wrong";
// Show JSON response
echo json_encode($response);
}
} else {
// If required parameter is missing
$response["success"] = 0;
$response["message"] = "Parameter(s) are missing. Please check the
request";
// Show JSON response
echo json_encode($response);
}
?>
and my db_connect.php :
<?php
class DB_CONNECT {
// Connecting to mysql (phpmyadmin) database
// Constructor
function __construct() {
// Trying to connect to the database
$this->connect();
}
// Destructor
function __destruct() {
// Closing the connection to database
$this->close();
}
// Function to connect to the database
function connect() {
//importing dbconfig.php file which contains database credentials
$filepath = realpath (dirname(__FILE__));
require_once($filepath."/dbconfig.php");
// Connecting to mysql (phpmyadmin) database
$con = mysqli_connect($dbhost_name, $username, $password);
// Selecing database
// returing connection cursor
return $con;
}
// Function to close the database
function close() {
// Closing data base connection
mysqli_close($con);
}
}
?>
and this is my link in postman I am using:
http://mydomain in hostinger.com/api/insert.php?temp=25&hum=80&time=2019-05-
09 08:00:00
and the result is:
{
"success": 1,
"message": "climate successfully created."
}
Is there any problem with my code?
Thanks for all
You haven't actually executed the query. $result is actually $query, and should be passed to your db connection $dbo.
I need simple web service to get data from local database, but when I've moved files from test server to actual server I just receive blank page with 'null' in top left corner.
My php code is very simple:
<?php
// Include config
require_once 'config/db.php';
$sql = new db();
$conn = $sql->connect();
$task = isset($_GET['task']) ? mysql_real_escape_string($_GET['task']) : "";
if(!empty($task))
{
if($task === "totals")
{
$qur = mysql_query("working query - no problem here;");
$result =array();
while($r = mysql_fetch_array($qur))
{
extract($r);
$result[] = array("total_value" => $total_value, 'orders_date' => $orders_date, 'number_of_orders' => $number_of_orders);
}
$json = $result;
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json, JSON_PRETTY_PRINT);
?>
And here is db.php code:
<?php
class db
{
// Properties
private $dbhost = 'ip-address';
private $dbuser = 'xxx';
private $dbpass = 'yyy';
private $dbname = 'zzz';
// Connect
public function connect()
{
$conn = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
mysql_select_db($this->dbname, $conn);
}
}
?>
May be Json_encode not giving correct answer.
1) Also please make sure JSON_PRETTY_PRINT is only available for PHP versions >= 5.4. It's value is 128, so try replacing JSON_PRETTY_PRINT with 128.
just on error reporting at top of page to debug
2) Also to make sure once try to print $json before encoding it
3) As mentioned in comment just encode only when you are actually getting data
!empty($json){
header('Content-type: application/json');
echo json_encode($json, JSON_PRETTY_PRINT);
}
I am creating an android app that was previously used with a MySQL database, however now I have to use a SQL Server database. Are there any applications or resources that can convert one to the other?
Here is an example of the php code I was using to connect to the MySQL database:
db_connect.php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
//require_once __DIR__ . '/db_config.php';
define('__ROOT__',dirname(dirname(__FILE__)));
require_once __ROOT__ . '/android_connect/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
create_product.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
// 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);
}
?>
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."));
}
}