使用AngularJS显示数据库中的数据

时间:2014-10-06 15:01:17

标签: php mysql database angularjs

我想在我的页面中显示db中的数据。

这是我的代码 JS

 $scope.save = function() {
   var data = {
     subject: $scope.composeStory.subject,
     body: $scope.composeStory.body
   }


   $http.post(
       "insert.php", {
         'subject': $scope.composeStory.subject,
         'body': $scope.composeStory.body
       }
     )
     .success(function(data, status, headers, config) {
       console.log("inserted Successfully");
     });
 };

Php

include('config.php');

$data = json_decode(file_get_contents("php://input"));
$subject = mysql_real_escape_string($data->subject);
$body = mysql_real_escape_string($data->body);
mysql_select_db("angular") or die(mysql_error());
mysql_query("INSERT INTO story (subject,body) VALUES ('$subject', '$body')");
Print "Your information has been successfully added to the database.";

$query = "SELECT * FROM story";
$result = mysql_query($query);

$arr = array();
while ($row = mysql_fetch_array($result)) {
    $subject = $row['name'];
    $body = $row['description'];
    $arr[] = $row;
}
echo json_encode($arr);  

Json

[{"0":"","subject":"","1":"","body":""},
 {"0":"","subject":"","1":"","body":""},
 {"0":"Soheil","subject":"Soheil","1":"Sadeghbayan","body":"Sadeghbayan"},
 {"0":"adsas","subject":"adsas","1":"asdasdasda","body":"asdasdasda"},
 {"0":"Say","subject":"Say","1":"Something","body":"Something"}]

它完全保存到db,但我不知道如何将数据从数据库显示到我的页面?

1 个答案:

答案 0 :(得分:0)

为了检索数据,创建一个工厂服务,使用$http GET方法,url指向你的php文件,该文件以下列格式返回$data数组:{{ 1}}

这是我在另一个问题上发布的最近一个例子:

echo json_encode($data);