2016-01-30 30 views
0

我是新來的Angular JS,我想從表單插入數據到MySQL數據庫表(在我的情況下表名是employe)但是當我點擊提交時,它沒有插入。我在瀏覽器中編譯insert.php文件,這給我這個錯誤「試圖獲得非對象的屬性」。我以JSON格式發送數據,然後我在index.php文件中解碼,但是當我試圖通過$data對象訪問解碼數據時,它給了我提到的錯誤。爲什麼我正在嘗試在AngularJs中獲取非對象錯誤的屬性?

myApp.js代碼

var app = angular.module('myApp',[]) 

.controller("myController",function($scope,$http){ 
    $scope.insertData = function(){ 
     $http.post("insert.php",{'name': $scope.name,'fname': $scope.fname,'dept': $scope.dept}) 
     .success(function(data,status,headers,config){ 
      console.log("Inserted Successfuly!"); 
     }); 
    } 
}); 

insert.php代碼

<?php 
$data = json_decode(file_get_contents("php://input")); 
$name = $data->name; 
$fname = $data->fname; 
$dept = $data->dept; 

$host = 'localhost'; 
$dbname = 'company'; 
$dbusername = 'root'; 
$dbpass = ''; 

$connection = mysqli_connect($host,$dbusername,$dbpass,$dbname); 

if (mysqli_connect_errno()){ 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
}else{ 
    $query = "INSERT INTO employe ('id','ename','fname','dept') VALUES('','$name','$fname','$dept')"; 
    $query_run = mysqli_query($connection,$query); 
} 
?> 

index.html的代碼

<html ng-app="myApp"> 

    <head> 
     <title> Using Angular with PHP! </title> 
     <!--<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script>--> 
     <style type="text/css" src="css/bootstrap.min.css"></style> 
    </head> 

    <body> 
     <div class="container"> 
      <div class="row"> 
       <div class="col-lg-12" ng-controller="myController"> 
        <form> 
         Your Name: <input type="text" ng-model="name" /><br><br> 
         Father Name: <input type="text" ng-model="fname" /><br><br> 
         Department : <input type="text" ng-model="dept" /><br><br> 
         <input class="btn btn-success" type="button" value="Submit" ng-click="insertData()" /> 
        </form> 
       </div> 
      </div> 
     </div> 


     <script type="text/javascript" src="js/angular/angular.min.js"></script> 
     <script type="text/javascript" src="js/bootstrap/bootstrap.min.js"></script> 
     <script type="text/javascript" src="js/app.js"></script> 
    </body> 
</html> 
+1

「我以JSON格式發送數據」 - 但你不是。試試'var_dump($ _ POST);'你會看到實際收到的內容。 – rjdown

+1

@rjdown所以這是什麼「$ http.post(」insert.php「,」線做?我傾銷$ _POST它打印出來「數組(0){}」我沒有得到。 –

+1

你試過嗎?打印出'file_get_contents(「php:// input」)'並查看它是否包含任何數據? –

回答

1

你會笑,但只需在表名稱周圍加上這些``就可以做好你的工作

$query = "INSERT INTO `employe`(`id`, `ename`, `fname`, `dept`) VALUES('','$name','$fname','$dept')"; 
相關問題