php - 查看变量是否在数组中

标签 php mysql

我正在使用 MySQL 数据库。我完全确定该 ID 确实存在于数据库中。为什么它会转到最后一个 else(哪里显示//不正确的 id)?

<?php
            //Localise user id.
            $userid = $_SESSION['userid'];

            //Get content of the article.
            $sql = "SELECT * FROM articles WHERE creatorid = '$userid'";
            $result = mysql_query($sql) or die(mysql_error()); //Execute. If fails, show error.
            $array = mysql_fetch_array($result);

            if(in_array($articleid, $array)) //If the URL id exists in the database (array)
            {
                //The article does actually exist for that user. They requested it.
                $sql = "SELECT * FROM articles WHERE id = '$articleid'";                
                $result = mysql_query($sql) or die(mysql_error()); //Execute. If fails, show error. 
                $array = mysql_fetch_array($result);

                        $content = $array['content'];

                        if($content != '') //If the article has actually been written.
                        {
                            include($_SERVER['DOCUMENT_ROOT'] . '/includes/renderimage.php');
                        }   else
                            {
                                //Article actually hasn't been written.
                            }
            }   else
                {
                    //Incorrect ID.
                }
                ?>

最佳答案

您只查看返回的第一行。您需要在循环中调用 mysql_fetch_array 来获取每一行。另外,您不应该使用 in_array(),因为文章 ID 可能会出现在其他列中(如果您要检查文章 #3 和用户 #3 怎么办?)。

但是,如果您只想查看该文章是否由该用户创建,则可以使用不同的查询:

SELECT * FROM articles WHERE creatorid = '$userid' AND articleid = '$articleid';

这应该返回 0 或 1 行,具体取决于用户是否创建了该文章。然后您可以使用 mysql_num_rows() 来测试这一点。

关于php - 查看变量是否在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12870578/

相关文章:

mysql - SQL - 在 SQL 中更改 "or ',以便更轻松地添加文本

mysql - 如何对每行中的所有行求和

php - Facebook SDK getAccessToken() 问题

php preg_match 验证价格格式

MySQL 获取除 If 之外的所有内容

php - 序列化失败: Deadlock found when trying to get lock

MySQL 语法错误,没有明显原因

php - 插入带有 Select 和附加参数的 stmt

php - 插入无值

PHP::检测 session 是否开始的最佳方法