如何删除此错误(!)警告:mysqli\u query():第28行的d:\wamp64\www\complete\u blog\u php\admin\includes\post\u functions.php中的空查询

mw3dktmi  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(331)
<?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;
    }
}
?>
j0pj023g

j0pj023g1#

如果这两个条件都失败:

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);

然后 $sql 变量未定义。如果必须这样做,那么可以检查是否设置了它们并返回默认值。

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";
}
if(!isset($sql)) return false; //or [] if you want the type to stay an array.
$result = mysqli_query($conn, $sql);

或者类似的,取决于你的需要。
也可以返回错误:

}else{
     return new WP_Error( 'restricted', __( "Not an Admin or Author", "my_textdomain" ) );
}

https://codex.wordpress.org/class_reference/wp_error
基本上就是这个 $_SESSION['user']['role'] 两者都不是 Admin 也不是一个 Author . 需要注意的一点是字符串匹配区分大小写。

相关问题