【发布时间】:2016-12-25 11:57:15
【问题描述】:
我正在尝试使用 Angular 工厂从我的 Wordpress 数据库中检索数据。使用ng-click="updateCommentsById(v.id.videoId)" 我调用以下函数:
$scope.updateCommentsById = function(id) {
commentRepository.query(({videoId: id}), function (data) {
$scope.comments = data;
});
}
对应于以下工厂定义:
angular.module("app")
.factory("commentRepository",
function($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php/:videoId",
{
videoId:"@id"
});
});
问题是如何将videoId 参数放入我在get_comments.php 内的PHP 函数中:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
echo $id;
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM analyser_posts WHERE video_id = $id", OBJECT);
echo wp_json_encode($result);
}
}
get_comments_by_id(videoId);
编辑:
原来 get_results() 方法不允许在 SQL 语句中使用变量,我应该使用 prepare() (无论如何更安全)。我还更改了请求 URL。新代码变为:
angular.module("app")
.factory("commentRepository",
function ($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php?video_id=:videoId");
});
和 PHP:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
var_dump($id);
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$result = $wpdb->prepare("SELECT * FROM analyser_posts WHERE video_id = $id", OBJECT);
var_dump($result);
$result_array = array();
if($result){
foreach($result_array as $r){
$result_array[] = $r;
}
}
var_dump($result_array);
echo json_encode($result_array);
}
}
get_comments_by_id($_GET["video_id"]);
然而 var_dumps 显示 id 被正确传递,只有 prepare() 实际上并没有执行任何操作。我应该将其包装在 get_results 中吗?
【问题讨论】:
标签: php mysql angularjs json wordpress