<?php
// Post variables
$post_id = 0;
$isEditingPost = false;
$published = 0;
$title = "";
$post_slug = "";
$body = "";
$featured_image = "";
$post_topic = "";
/* - - - - - - - - - -
- Post functions
- - - - - - - - - - -*/
// get all posts from DB
function getAllPosts()
{
global $conn;
// Admin can view all posts
// Author can only view their posts
if ($_SESSION['user']['role'] == "Admin") {
$sql = "SELECT * FROM posts";
} elseif ($_SESSION['user']['role'] == "Author") {
$user_id = $_SESSION['user']['id'];
$sql = "SELECT * FROM posts WHERE user_id=$user_id";
}
$result = mysqli_query($conn, $sql);
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
$final_posts = array();
foreach ($posts as $post) {
$post['author'] = getPostAuthorById($post['user_id']);
array_push($final_posts, $post);
}
return $final_posts;
}
// get the author/username of a post
function getPostAuthorById($user_id)
{
global $conn;
$sql = "SELECT username FROM users WHERE id=$user_id";
$result = mysqli_query($conn, $sql);
if ($result) {
// return username
return mysqli_fetch_assoc($result)['username'];
} else {
return null;
}
}
?>
1条答案
按热度按时间j0pj023g1#
如果这两个条件都失败:
然后
$sql
变量未定义。如果必须这样做,那么可以检查是否设置了它们并返回默认值。或者类似的,取决于你的需要。
也可以返回错误:
https://codex.wordpress.org/class_reference/wp_error
基本上就是这个
$_SESSION['user']['role']
两者都不是Admin
也不是一个Author
. 需要注意的一点是字符串匹配区分大小写。