2

I am attempting to test inserting in a database using a restful web service. I followed this tutorial https://trinitytuts.com/build-first-web-service-php/ Whenever I post the data I get back successful but the database doesn't display the information (IE it created an entry but all the fields are blank). I am 75% sure it is the Advanced Rest Client but I don't know whats wrong with it. Here's the code/Post command.

Post string is name=Apple&email=banna%40orange.com&pwd=12345&status=ok, Picture of how I send it using Advanced Rest Client.

enter image description here

confi.php file

 <?php
 $conn = mysqli_connect("localhost", "root", "", 'tuts_rest');
 ?>

Rest of the code

        <?php

include_once('confi.php');

if($_SERVER['REQUEST_METHOD'] == "POST"){
$name = isset($_POST['name']) ? mysqli_real_escape_string($_POST['name']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : "";
$password = isset($_POST['pwd']) ? mysqli_real_escape_string($_POST['pwd']) : "";
$status = isset($_POST['status']) ? mysqli_real_escape_string($_POST['status']) : "";

 // Insert data into data base
 $sql = "INSERT INTO users (ID, name, email, password, status) VALUES ('' , '" . $name . "', '" . $email . "', '" . $password . "', '" . $status . "');";
 $qur = $conn->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");
}

mysqli_close($conn);

/* Output header */
 header('Content-type: application/json');
 echo json_encode($json);
?>

Thank you!

4
  • If you can, you should stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO, it's really not hard. Commented Jul 7, 2015 at 15:03
  • 1
    $sql = "INSERT INTO users (ID, name, email, password, status) VALUES ('' , '" . $name . "', '" . $email . "', '" . $password . "', '" . $status . "');"; Commented Jul 7, 2015 at 15:03
  • Please don't post screenshots, especially illegible ones, unless the presentation is relevant to the question. Also that tutorial is teaching you extremely bad habits, that style of PHP is straight out of the 1990s, so please don't use it. A guide like PHP the Right Way can help explain modern best practices. Learning and using a development framework like Laravel will significantly help your productivity. Commented Jul 7, 2015 at 15:52
  • WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you will create severe SQL injection bugs. NEVER put $_POST data directly into a query and avoid using manual escaping because a single mistake can create total chaos. Commented Jul 7, 2015 at 15:52

3 Answers 3

3

Instead of this use my code(I change all of your code and add extra security whether you can remove the header as you wish). here you can easily insert the data from json format into database. in Advance rest client you see there is a button Raw where you can write json data type. For this example,

{
      "name": "Ashraf",
      "email":"[email protected]",
      "pwd": "1234",
      "status": "nice"
  }

Now click send button and see your data will be inserted in your database

<?php

// Include confi.php
include_once('confi.php');
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
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");
	// Get data
	$content=trim(file_get_contents("php://input"));
	$data = json_decode($content, true);

if(
    !empty($data['name']) &&
    !empty($data['email']) &&
    !empty($data['pwd']) &&
    !empty($data['status'])
){
	$name=$data['name'];
	$email=$data['email'];
	$password=$data['pwd'];
	$status=$data['status'];


	// Insert data into data base
	$sql = "INSERT INTO users (name, email, password, status) VALUES (? , ?, ?, ?)";
	$qur=mysqli_query($conn,$sql);
	
//sanitize
	  $name=htmlspecialchars(strip_tags($name));
       $email=htmlspecialchars(strip_tags($email));
       $password=htmlspecialchars(strip_tags($password));
       $status=htmlspecialchars(strip_tags($status));
  	//bind values 
   $stmt = $conn->prepare($sql);
  	if($stmt)
  	{	
	  	$stmt->bind_param("ssss", $name, $email, $password,$status);
		
		if($stmt->execute())
		{
			$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);
?>

Sign up to request clarification or add additional context in comments.

Comments

1

Because you are using mysql_real_escape_string. The function is deprecated. You may use mysqli_real_escape_string instead of that.

3 Comments

Try to catch all errors and you may get the error message. by error_reporting(E_ALL);
Good catch, tried to update to all mysqli but seems I missed that important one. Didn't fix it though sadly, I think it has something to do with my _Post payload.
NO. Do not use addslashes for anything related to SQL.
0

Thanks for all the help guys! I have it working though I do not understand it. The problem was indeed in my Advanced Rest Client application. I was sending the payload as application/json and it wasn't getting the POST data but when I changed the Content-Type to application/x-www-form-urlencoded it worked. If anyone wants to explain why that fixed it I will appreciate it and I'm sure others will as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.