我试图使用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_dump显示id正确传递,只有prepare()实际上没有执行任何操作。我应该将它包装在get_results中吗?
答案 0 :(得分:1)
您可以从URI中提取它:
//$args is an array of every part separated by `/` (ignoring the query string)
$args = explode('/',strtok(trim($_SERVER['REQUEST_URI'],'/'),'?'));
//the last element is the video id
$video_id = end($args);
答案 1 :(得分:0)
使用答案(包括现已删除的答案)和评论来使用它。我的Angular控制器代码中的函数:
$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?video_id=:videoId");
});
get_comments.php:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$sql = $wpdb->prepare("SELECT * FROM `analyser_posts` WHERE `video_id` = '$id'", OBJECT);
$result = $wpdb->get_results($sql);
echo json_encode($result);
}
}
get_comments_by_id($_GET["video_id"]);