POST data is not being received in API call - php

I have built an API on PHP. While sending a POST request, variables provided in POST url are not being received and input data-set is empty. data variable in below provided create.php is empty.
If we supply hard coded data in create PHP file, then it is working fine.
Below is my main data.php file code. Which contains the function for creating the product using POST variables.
<?php
class Data{
private $conn;
private $table_name = "data";
public $id;
public $email;
public $address;
public $lasttx;
public $created;
public function __construct($db){
$this->conn = $db;
}
function create(){
$query = "INSERT INTO " . $this->table_name . " SET email=:email,
address=:address, lasttx=:lasttx, created=:created";
$stmt = $this->conn->prepare($query);
$this->email=htmlspecialchars(strip_tags($this->email));
$this->address=htmlspecialchars(strip_tags($this->address));
$this->lasttx=htmlspecialchars(strip_tags($this->lasttx));
$this->created=htmlspecialchars(strip_tags($this->created));
$stmt->bindParam(":email", $this->email);
$stmt->bindParam(":address", $this->address);
$stmt->bindParam(":lasttx", $this->lasttx);
$stmt->bindParam(":created", $this->created);
if($stmt->execute()){
return true;
}
return false;
}
Below is the code of create.php which is being called in API calls. This file receives data and calls create function in data.php
<?php
header("Access-Control-Allow-Origin: *");
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");
include_once '../config/database.php';
include_once '../objects/data.php';
$database = new Database();
$db = $database->getConnection();
$data1 = new Data($db);
$data = json_decode(file_get_contents("php://input"), true); // THIS VARIABLE is EMPTY while calling API.
$data1->email = $data["email"];
$data1->address = $data["address"];
$data1->lasttx = $data["lasttx"];
$data1->created = date('Y-m-d H:i:s');
if($data1->create()) {
echo '{';
echo '"message": "Product was created."';
echo '}';
}
else{
echo '{';
echo '"message": "Unable to create product."';
echo '}';
}
?>
Please Advise. Many thanks.

u
as you point out in your comment the form variables are submitted via the URL. In your above script, you're trying to parse a JSON object that is the payload of the request. And that's just not where these parameters are - hence you don't get any data from there.
To access variables from the URL in PHP, all you need to do is to get them from the $_GET array. e.g. the email would be in $_GET["email"].
so this part here:
$data = json_decode(file_get_contents("php://input"), true); // THIS VARIABLE is EMPTY while calling API.
$data1->email = $data["email"];
$data1->address = $data["address"];
$data1->lasttx = $data["lasttx"];
$data1->created = date('Y-m-d H:i:s');
will become:
# $data = json_decode line goes away
$data1->email = $_GET["email"];
$data1->address = $_GET["address"];
$data1->lasttx = $_GET["lasttx"];
$data1->created = date('Y-m-d H:i:s');
hope this helps
Matthias

Related

Can't perform a PHP POST request on mysql database

I'm struggling into do my first API in php and I'm facing some problems with a simple POST request. I've searched almost everywhere for some alternatives to my code, but it seems to be ok. Can you guys check it for me the last time? Thank you!
method:
function create_msg(){
// query to insert record
$query = "INSERT INTO
" . $this->table_name . "
SET
msg_key=:msg_key, msg_id=:msg_id, msg_author=:msg_author, msg_txt=:msg_txt";
// prepare query
$stmt = $this->conn->prepare($query);
// sanitize
$this->msg_key=htmlspecialchars(strip_tags($this->msg_key));
$this->msg_id=htmlspecialchars(strip_tags($this->msg_id));
$this->msg_author=htmlspecialchars(strip_tags($this->msg_author));
$this->msg_txt=htmlspecialchars(strip_tags($this->msg_txt));
// bind values
$stmt->bindParam(":msg_key", $this->msg_key);
$stmt->bindParam(":msg_id", $this->msg_id);
$stmt->bindParam(":msg_author", $this->msg_author);
$stmt->bindParam(":msg_txt", $this->msg_txt);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
create.php:
<?php
header("Access-Control-Allow-Origin: *");
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");
include_once '../config/database.php';
include_once '../models/msg.php';
$database = new Database();
$db = $database->getConnection();
$item = new msg($db);
$data = json_decode(file_get_contents("php://input"));
$item->msg_key = $data->msg_key;
$item->msg_id = $data->msg_id;
$item->msg_author = $data->msg_author;
$item->msg_txt = $data->msg_txt;
var_dump($data);
if($item->create_msg()){
echo 'OK';
} else{
echo 'Not OK';
}
?>
ok, so I managed to resolve with this code in the config/database.php
<?php
class Database{
private $host = 'mysql:host=localhost;dbname=my_touchy';
private $username = 'touchy';
private $password = '';
public function getConnection() {
$conn = new PDO($this->host, $this->username, $this->password);
$conn->setAttribute( PDO::ATTR_PERSISTENT, TRUE );
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
return $conn;
}
}
?>

Getting a http_response_code(404) when trying to pass a record id dynamically in phpmyadmin. Am trying to integrate MySQL on-pre with Salesforce

I am trying to update one particular record or row corresponding to a id passed dynamically. There is a record belonging to that id. When I give the URL followed with the "?id=3", I am getting a 404 error, saying no such record exists. Would like to know what error I have done. The following is my code.
<?php
header("Access-Control-Allow-Origin: *");
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");
include_once '../config/database.php';
include_once '../objects/constitute.php';
$database = new Database();
$db = $database->getConnection();
$constitute = new Constitute($db);
$data = json_decode(file_get_contents("php://input"));
$constitute->id = isset($_GET['id']) ? $_GET['id'] : die();
$constitute->name = $data->name;
$constitute->address = $data->address;
$constitute->constitution_type = $data->constitution_type;
$constitute->organisation_id = $data->organisation_id;
if($constitute->update()){
http_response_code(200);
echo json_encode(array("message" => "Constitute was updated."));
}
else{
http_response_code(503);
echo json_encode(array("message" => "Unable to update constitute."));
}
?>
The following is the update() method:
function update(){
$query = "UPDATE
" . $this->table_name . "
SET
name = :name,
address = :address,
constitution_type = :constitution_type,
organisation_id = :organisation_id
WHERE
id = ?";
$stmt = $this->conn->prepare($query);
$this->id=htmlspecialchars(strip_tags($this->id));
$this->name=htmlspecialchars(strip_tags($this->name));
$this->address=htmlspecialchars(strip_tags($this->address));
$this->constitution_type=htmlspecialchars(strip_tags($this->constitution_type));
$this->organisation_id=htmlspecialchars(strip_tags($this->organisation_id));
$stmt->bindParam(':id', $this->id);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':address', $this->address);
$stmt->bindParam(':constitution_type', $this->constitution_type);
$stmt->bindParam(':organisation_id', $this->organisation_id);
if($stmt->execute()){
return true;
}
return false;
}
Also when i try to pass the updated record in postman, I am getting success code. But the record does not get saved.
Please let me know where I have done mistakes.

How else can I debug/rewrite the code below

I am building a user api and one of the task is to create user by inserting a user into the database but while I came up with a code it worked, but it returned 400 bad request as oppose to 200 ok status
create_user.php
<?php
// required headers
header("Access-Control-Allow-Origin: http://localhost/portal/user/");
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");
// database connection will be here
// files needed to connect to database
include_once 'config/database.php';
include_once 'objects/user.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// instantiate product object
$user = new User($db);
// submitted data will be here
// get posted data
$data = json_decode(file_get_contents("php://input"));
// set product property values
$user->first_name = $data->first_name;
$user->last_name = $data->last_name;
$user->email = $data->email;
$user->password = $data->password;
$user->mobile_no = $data->mobile_no;
// use the create() method here
// create the user
if(
!empty($user->first_name)&&
!empty($user->last_name)&&
!empty($user->email)&&
!empty($user->password)&&
!empty($user->mobile_no)&&
$user->create()
){
// set response code
http_response_code(200);
// display message: user was created
echo json_encode(array("message" => "User was created."));
}
// message if unable to create user
else{
// set response code
http_response_code(400);
// display message: unable to create user
echo json_encode(array("message" => "Unable to create user."));
}
user.php (class)
<?php
// 'user' object
class User{
// database connection and table name
private $conn;
private $table_name = "users";
// object properties
public $uid;
public $first_name;
public $last_name;
public $email;
public $password;
public $mobile_no;
// constructor
public function __construct($db){
$this->conn = $db;
}
// create() method will be here
// create new user record
function create(){
// insert query
$query = "INSERT INTO " . $this->table_name . "
SET
first_name = :first_name,
last_name = :last_name,
email = :email,
password = :password,
mobile_no = :mobile_no";
// prepare the query
$stmt = $this->conn->prepare($query);
// sanitize
$this->first_name=htmlspecialchars(strip_tags($this->first_name));
$this->last_name=htmlspecialchars(strip_tags($this->last_name));
$this->email=htmlspecialchars(strip_tags($this->email));
$this->mobile_no=htmlspecialchars(strip_tags($this->mobile_no));
$this->password=htmlspecialchars(strip_tags($this->password));
// bind the values
$stmt->bindParam(':first_name', $this->first_name);
$stmt->bindParam(':last_name', $this->last_name);
$stmt->bindParam(':email', $this->email);
$stmt->bindParam(':mobile_no', $this->mobile_no);
// hash the password before saving to database
$password_hash = password_hash($this->password, PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password_hash);
// execute the query, also check if query was successful
if($stmt->execute()){
return true;
}
return false;
}
}
?>
I expect to see a status code of 200 ok since i have inserted some values inside the body of the postman request. it was suppose to return 400 bad request if the values are empty

PHP server not receiving JSON array from Swift

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.

How to insert json array into mysql database

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."));
}
}

Categories