PHP Post Webservice Issue - php

Trying to implement a post webservice in PHP so that finally it can be used in ios app for communicating to DB. Can you please identify the mistake.
Please find the code below. It is saying that "Request Method not accepted" status 0 returned
<?php
// Create connection
$con=mysqli_connect("myhost.com","myuser","mypassword","mydb");
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$lat= isset($_POST['lat']) ? mysql_real_escape_string($_POST['long']) : "";
$long= isset($_POST['long']) ? mysql_real_escape_string($_POST['long']) : "";
$timeStamp = isset($_POST['timeStamp']) ? mysql_real_escape_string($_POST['timeStamp']) : "";
$deviceId = isset($_POST['deviceId']) ? mysql_real_escape_string($_POST['deviceId']) : "";
// Insert data into data base
$sql = "INSERT INTO `gpsReporting` (`lat`, `long`, `timeStamp`, `deviceId`) VALUES ('$lat', '$long', '$timeStamp', '$deviceId');";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);

Related

why i cant get the json from this scrip in php using alamofire?

i wrote this script to sign in the user in PHP in order to save the data to the server, if the user has been created the scrip should return a simple json with true or false.
<?php
require "../private/autoload.php";
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
print_r($_POST);
$Error = "";
$staff = $_POST['staff_ID'];
$email = $_POST['email'];
$pass = $_POST['password'];
$name = $_POST['Name'];
$cpt = $_POST['isCPT'];
$date = date("Y-m-d H:i:s",time()); // date of creation
// check if user alrady exixt
$sqlexixst = "SELECT * FROM `users` WHERE staff_ID = ?";
$st = $pdo->prepare($sqlexixst);
$st->execute(array($staff));
$result = $st->fetchAll();
if (count($result) > 0){
$array = array(
"user_created"=>false
);
$js = json_encode($array);
echo $js;
} else {
// user not exixt creo utente
$regex = '/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex,$email)){
// ok email
if (is_numeric($staff)){
// ok id
$sql = "INSERT INTO users (staff_ID,password,email,isCPT,Name, date) VALUES (?,?,?,?,?,?)";
$statement = $pdo->prepare($sql);
$statement ->execute([$staff,$pass,$email,$cpt,$name,$date]);
$array = array(
"user_created"=>true,
"staff_ID"=>$staff
);
$js = json_encode($array);
echo $js;
}
}else{
$Error = "pls enter valid email";
echo $Error;
}
}
}else {
echo 'no post';
}
?>
i'm sending the request using Alamofire... if i post the request using respondeString i can see the corret print out of the json, if i use respondJSON i cant get the json print out.. i get error say 'JSON could not be serialized. thata could not be read because it isn't in the correct format'
Alamofire and swiftyjson code:
func nxTest (){
let parm : [String : Any] = ["staff_ID": "3879","password":"12345678","email":"damiano.miai#gmail.com", "isCPT":false,"Name":"Marco Frizzi"]
AF.request("http://192.168.50.10/nx/public/register.php", method: .post, parameters: parm,headers: nil, interceptor: nil, requestModifier: nil).validate()
.responseJSON { js in
switch js.result {
case .success(let value) :
let json = JSON(value)
debugPrint(json)
case .failure(let err) :
debugPrint(err.localizedDescription)
}
}
.responseString { st in
print(st)
}
}

Can't post the values in 000webhost phpmyadmin database [duplicate]

This question already has answers here:
mysqli_real_escape_string() expects exactly 2 parameters, 1 given
(5 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I am trying to post the value in my database's table which i have made in 000webhost phpmyadmin server.To post/check i am using the postman software.
In postman software i am passing the key value pairs (in form-data selection and also tried to pass in x-www-form-urlencoded). But values getting added are null. not that i have pass in key value pairs.
And when i am passing without any key value pair it still adds the row with null values in my table.
Please help to solve..
I making this api to use it in my android application.
Here in my php code:
confi.php:
<?php
error_reporting(1);
$conn = mysqli_connect("localhost", "********", "******","id1536885_mydb");
?>
individualuser_details.php:
<?php
// Include confi.php
include_once('confi.php');
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$name = isset($_POST['name']) ? mysqli_real_escape_string($_POST['name']) : "";
$adhar = isset($_POST['adhar']) ? mysqli_real_escape_string($_POST['adhar']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ? mysqli_real_escape_string($_POST['password']) : "";
$contact = isset($_POST['contact']) ? mysqli_real_escape_string($_POST['contact']) : "";
$status = isset($_POST['status']) ? mysqli_real_escape_string($_POST['status']) : "";
//echo $name.' no';
// Insert data into data base
$sql ="INSERT INTO id1536885_mydb.`individualuser_details` (`ID`, `name`, `adhar`, `email`, `password`, `contact`, `status`) VALUES (NULL, '$name', '$adhar', '$email', '$password', '$contact', '$status');";
// echo $sql;
$qur = mysqli_query($conn,$sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysqli_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>

PHP - JSON empty values in database

I am very new to php. I wan't to create json service which will be responsible to save registration form values in database. The problem is, it saves empty values in database. The problem is I can't understand how to get values from json and save them in database
php code
<?php
// Include confi.php
include_once('confi.php');
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) :'';
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
$password = isset($_POST['pwd']) ? mysql_real_escape_string($_POST['pwd']) : '';
$status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : '';
// Insert data into data base
$sql = "INSERT INTO `test`.`users` (ID,`name`, `email`, `password`, `status`) VALUES (NULL,'$name', '$email', '$password', '$status');";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
Sending values with post method
{
"name":"aamir",
"email":"a#a.com",
"pwd":"12345678",
"status":"yes"
}
This is the result
and I have followed this link
https://trinitytuts.com/build-first-web-service-php/
From my opinion you have problems with client-server interactions.
PHP did not parse JSON data, it work only with url-encoded values.
So, your $_POST variable is empty array.
To get JSON formatted values, you should use
$post = json_decode(file_get_contents('php//input'), true));

Adding data to database

When I try to add a user to the database with POST a new user is added but all fields are Null.
Any help guys ? Thank you in advance.This is my source code:
if($_SERVER['REQUEST_METHOD'] == "POST")
{
// Get data
$name = isset($_POST['name']) ;
$email = isset($_POST['email']);
$password = isset($_POST['password']);
$status = isset($_POST['status']);
// Insert data into data base
$sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$name', '$email', '$password', '$status')";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
**
isset return only true or false so if you want to insert value you can check it with if condition replace your code with above it will be work fine
if($_SERVER['REQUEST_METHOD'] == "POST"){
$name = (isset($_POST['name']))?$_POST['name']:'' ;
$email = (isset($_POST['email']))?$_POST['email']:'';
$password = (isset($_POST['password']))?$_POST['password']:'';
$status = (isset($_POST['status']))?$_POST['status']:'';
$sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$name', '$email', '$password', '$status')";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
header('Content-type: application/json');
echo json_encode($json);
save this form in html file and check it with this edited example
<form method="post">
<input type="text" name="name" value="Red Symbol" />
<input type="text" name="email" value="red#symbol.com" />
<input type="text" name="password" value="chock" />
<input type="text" name="status" value="1" />
<input type="submit" name="submit" value="Submit" />
</form>
You are not checking if any of the fields are empty.
You need to do that, and only perform the query if they are not.
You can also restructure your code to avoid nested if/else:
function sendJson($data){
header('Content-type: application/json');
echo json_encode($data);
//stop execution after sending response
exit;
}
//if not POST request, exit
if($_SERVER['REQUEST_METHOD'] !== "POST") {
sendJson(["status" => 0, "msg" => "Request method not accepted"]);
}
//default data
$defaults = [
'name' => false,
'email' => false,
'password' => false,
'status' => false,
];
$input = array_intersect_key(array_merge($defaults, $_POST), $defaults);
//if empty field, exit
if(in_array(false, $input)){
sendJson(["status" => 0, "msg" => "All fields are required"]);
}
// Insert data into data base
//you REALLY REALLY need to use PDO/MYSQLI with prepared statements, this code is dangerous
$sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$input[name]', '$input[email]', '$input[password]', '$input[status]')";
$qur = mysql_query($sql);
//if query failed, exit
if(!$qur){
sendJson(["status" => 0, "msg" => "Error adding user!"]);
}
//if we get here, all is OK
sendJson(["status" => 1, "msg" => "Done User added!"]);
#mysql_close($conn);

MySQL query not working with PHP

I have a code in PHP where a field value entered should match with the values in a table in a database. If match found it must do some work, or else it must say "match was not found".
But whenever I check with values which are not in the table (database), it says "match has been found".
Here is the code:
<?php
include"conn.php";
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
// Vehicle Number
$vehicle_number = isset($_POST['VehicleNumber']) ?mysql_real_escape_string($_POST['VehicleNumber']) : "";
//ID card Nos.
$idcardno1= isset($_POST['idno1']) ? mysql_real_escape_string($_POST['idno1']) : "";
$idcardno2= isset($_POST['idno2']) ? mysql_real_escape_string($_POST['idno2']) : "";
//Text Messages
$Textmsg = isset($_POST['yourtext']) ? mysql_real_escape_string($_POST['yourtext']) : "";
if($idcardno1 == NULL )
{
//echo "Blank Fields";
$json = array("status" => "Failure", "msg" => "User has entered one or more than one null values so couldn't go for database operations");
}
else
{
$q=mysql_query("SELECT * FROM profile WHERE IDcardno1 ='$idcardno1' OR IDcardno2 = '$idcardno2' OR VehicleNumber ='$vehicle_number'" )or die(mysql_error());
if($q)
{
$num=mysql_num_rows($q);
if($num==0)
{
$json = array("status" => "Failure", "msg" => "Information not found");
print $num;
}
else{
$json = array("status" => "success", "msg" => "Information is stored and match has been found");
}
}
}
}
else{
$json = array("status" => "Failure", "msg" => "POST_Request method not accepted");
}
mysql_close($con);
/* Output header */
//header('Content-Type: application/json');
echo json_encode($json);
?>
Because you are using OR in your SQL query, it will return any database rows where there is an empty database value and empty form value. This may return rows where you were not expecting them (depending on your intention)
If that's the case, you may want to ONLY match on field values that are actually populated by changing the query to something like this:
$q = mysql_query("SELECT * FROM profile WHERE (IDcardno1 ='$idcardno1' AND '$idcardno1' <> '') OR (IDcardno2 = '$idcardno2' AND '$idcardno2' <> '') OR (VehicleNumber ='$vehicle_number' AND '$vehicle_number' <> '')" )or die(mysql_error());
(This is just one way to approach it)

Categories