我正在尝试使用 PHP 和 AngularJS 从 MySql 数据库读取数据。
我的代码是
index.html
<!doctype html>
<html ng-app = "myModule">
<head>
<script src="../bower_components/angular/angular.min.js"></script>
<script src="Script.js"></script>
<script src="factory.js"></script>
<link href="Styles.css" rel="stylesheet">
</head>
<body ng-controller="myController">
<table ng-bind="readEmployees()">
<thead>
<tr>
<th >Name</th>
<th >Gender</th>
<th >Salary</th>
<th >City</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.salary}}</td>
<td>{{employee.city}}</td>
</tr>
</tbody>
</table>
</body>
</html>
脚本.js
var myApp = angular.module("myModule",[])
.controller("myController", function($scope, $http){
$scope.readEmployees = function(){
webservicefactory.readEmployees().then(function successCallback(response){
$scope.employees = response.data.records;
$scope.showToast("Read success.");
}, function errorCallback(response){
$scope.showToast("Unable to read record.");
});
}
});
工厂.js
app.factory("webservicefactory", function($http){
var factory = {
readEmployees : function(){
return $http({
method: 'GET',
url: 'http://localhost/AngularJS/webservice/webservice.php'
});
}
};
return factory;
});
werservice.php
<?php
$file = "test.txt";
$fh = fopen($file, 'w') or die("can't open file");
$con = mysql_connect("localhost","root","xxxxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Employees", $con);
$article_id = $_GET['id'];
if( ! is_numeric($article_id) )
die('invalid article id');
$query = "SELECT * FROM tblEmployees";
$returns = mysql_query($query);
// Please remember that mysql_fetch_array has been deprecated in earlier
// versions of PHP. As of PHP 7.0, it has been replaced with mysqli_fetch_array.
$returnarray = array();
while($return = mysql_fetch_array($returns, MYSQL_ASSOC))
{
$returnarray[] = $return;
}
fclose($fh);
mysql_close($con);
?>
我当前的问题是factory.js 中的readEmployees : function()
函数未被调用。
怎么了?
编辑:
现在我删除了factory.js并从Script.js获取数据
var myApp = angular.module('myModule', []);
myApp.controller('myController', function ($scope, $http){
$http.get('webservice.php').success(function(data) {
$scope.employees = data;
});
});
错误已更改为
最佳答案
第一个 php mysql_connect() 几乎已被弃用,现在您最常使用 pdo()
尝试
$db = new PDO('dblib:host=your_hostname;dbname=your_db;$user, $pass);
所以如果我明白你想通过 id 找到一篇文章
所以你有正确的方法来做到这一点,而不是这样 转到 php 文档并找到“bindValue” 这里:http://php.net/manual/en/pdostatement.bindvalue.php
重新组织你的 php 人员,即使这个人员是数字,如果你使用 pdo 类的语句,你不需要 你可以在你的绑定(bind)中写 PDO::PARAM_INT ,如果找到你需要的所有东西,这只接受 php doc 上请求 diggy 中的数字:) 关于 Angular ,我认为当你在 php 上提供正确的数据时,一切都很好
关于javascript - 使用 PHP 和 AngularJS 从 MySql 数据库读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44752117/