如何从数据库中检索非空值

时间:2014-03-23 13:09:53

标签: php mysql

我试图从我的表中检索非空值。下面是我的桌子forumposts的图片。

forumposts table

我想检索所有非空的线程标题。我使用以下代码:

$forum_activities = "";
$sql = "SELECT thread_title FROM forumposts WHERE thread_title IS NOT NULL";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0)
{
    while($row = mysqli_fetch_array($query,MYSQLI_ASSOC))
    {
        $thread_titles = $row["thread_title"];
        $forum_activities .= "<a href='viewthread.php'>$thread_titles</a><hr />";
    }
}

空值仍然存在。请帮忙!!

3 个答案:

答案 0 :(得分:2)

thread_title成为

varchar(255) and Default value is NULL 

并使用您的查询

CREATE TABLE IF NOT EXISTS `forumposts` (
  `thread_title` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `forumposts` (`thread_title`) VALUES
('foo'),
('bar'),
(NULL);

SELECT thread_title FROM forumposts WHERE thread_title IS NOT NULL

<强>输出

THREAD_TITLE

foo
bar

HERE IS THE WORKING SQL FIDDLE

答案 1 :(得分:1)

应该是这样的:

$sql = "SELECT thread_title FROM forumposts WHERE thread_title"; //Remove the IS NOT NULL
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0)
{
    while($row = mysqli_fetch_array($query,MYSQLI_ASSOC))
    {
        $thread_titles = $row["thread_title"];
        $forum_activities .= "<a href='viewthread.php'>$thread_titles</a><hr />";
    }
}

答案 2 :(得分:0)

您可以将其更改为:

$sql = "SELECT thread_title FROM forumposts WHERE thread_title != ''";

将选择与空字符串不同的任何内容。