MYSQL/PHP SELECT DISTINCT

孤人 提交于 2019-12-13 11:04:35

问题


I have this function called on another page.

function adminnav (){
    $pagewcoms = mysql_query("SELECT DISTINCT pageid FROM comments") or die(mysql_error());
    $idnavrow = mysql_fetch_row($pagewcoms);
    while ($itest = mysql_fetch_row($pagewcoms)) {
        echo "$itest[0] <br />";
    }
}

adminnav('');

The table is.

CREATE TABLE `comments` (
  `commentid` int(5) NOT NULL auto_increment,
  `pageid` int(5) NOT NULL default '0',
  `name` text NOT NULL,
  `email` text NOT NULL,
  `comment` text NOT NULL,
  `date` datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`commentid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=481 ;

INSERT INTO `comments` VALUES(480, 1, '3', '3', '3', '2011-09-13 22:43:06');
INSERT INTO `comments` VALUES(479, 1, '2', '2', '2', '2011-09-13 22:43:01');
INSERT INTO `comments` VALUES(476, 1, '1', '1', '1', '2011-09-13 17:22:49');
INSERT INTO `comments` VALUES(477, 2, 'taylordcraig', 'taylordcraig@gmail.com', 'this is page two', '2011-09-13 17:26:09');
INSERT INTO `comments` VALUES(478, 3, 'this is page3', 'this is page3', 'this is page3', '2011-09-13 22:28:59');

It's only pulling two results. "2 3" [I asked this before but worded it poorly.]


回答1:


Looks like the query is actually pulling 3 results as it should. You are just letting one of them go:

function adminnav (){
    $pagewcoms = mysql_query(...);

    // HERE YOU FETCH ONE ROW BUT DO NOTHING WITH IT
    $idnavrow = mysql_fetch_row($pagewcoms);

    while ($itest = mysql_fetch_row($pagewcoms)) {
        echo "$itest[0] <br />";
    }
}

If you just remove that line, or tweak it a little, it should display everything just fine:

function adminnav (){
    $pagewcoms = mysql_query(...);
    $idnavrow = null;

    while ($itest = mysql_fetch_row($pagewcoms)) {
        if (empty($idnavrow)) {
            $idnavrow = $itest;
        }
        echo "$itest[0] <br />";
    }
}


来源:https://stackoverflow.com/questions/7412157/mysql-php-select-distinct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!