如何将json数据从角度js传递给php

时间:2016-10-02 04:35:31

标签: php angularjs

我已经尝试了所有的可能性。我无法在php中读取json对象。我正确地将json数据传递给PHP?我已经使用$ _POST,$ _ REQUEST和json_decode来获取数据。没有用。如何在PHP中获取json数据? Controller.js

if (userValid==true)
                {
                  var data = {"firstName":user.firstName,
                       "lastName":user.lastName,
                       "mobileNumber":user.mobileNumber,
                       "email":user.email,
                       "type":user.type,
                       "password":user.password
                      };
                  $http.post("http://localhost/insertUser.php",data)                                      
                       .then(function(response){
                          alert(response.data);
                       });
           }

insertUser.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = '';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $user = json_decode(file_get_contents("php://input"));
   $firstName = mysql_real_escape_string($user->firstName);
   $lastName = mysql_real_escape_string($user->lastName);
   $mobileNumber = mysql_real_escape_string($user->mobileNumber);
   $email = mysql_real_escape_string($user->email);
   $type = mysql_real_escape_string($user->type);
   $password = mysql_real_escape_string($user->password);



      $sql = "INSERT INTO user ".
      "VALUES ('".$firstName."','".$lastName."','".$mobileNumber."','".$email."','".$type."','".$password."')";
   mysql_select_db('user_details');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not enter data: ' . mysql_error());
   }

   echo "Entered data successfully\n";

   mysql_close($conn);
?>

1 个答案:

答案 0 :(得分:0)

<?php
// header("Access-Control-Allow-Origin: *");
// header("Content-Type: application/json; charset=UTF-8");

$host     = "localhost";
$username = 'root';
$password = '';
$db_name  = 'user_details';
$connection = mysqli_connect("$host", "$username", "$password","$db_name") or die("cannot connect");
if ($connection) {
} else {
die('Could not connect: ' . mysqli_error());
}
$user         = json_decode(file_get_contents("php://input"));
$firstName    = $user->firstName;
$lastName     = $user->lastName;
$mobileNumber = $user->mobileNumber;
$email        = $user->email;
$type         = $user->type;
$password     = $user->password;
$sql          = "INSERT INTO user(firstname,lastname,mobile,email,type,password)VALUES('$firstName','$lastName','$mobileNumber','$email','$type','$password')";
$result       = mysqli_query($connection, $sql);
if (!$result) {
 die('Could not enter data: ' . mysql_error());
} else {
echo "Entered data successfully\n";
}
?>

使用此作为您的PHP。希望它会工作。让我知道它是否有效。并根据你的表更改列名。谢谢:))