为什么这个mysql查询不起作用?

时间:2012-04-21 16:29:01

标签: php mysql

请帮我解决指定的问题:

代码部分:

$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,    
  UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where 
  id='$_GET[id];'");

// the above query is not working   

if ( mysql_num_rows($result) == 0 ) {  
   print "<p>No events right now.</p>\n";
   }
else {

    $lasteventmonth = '';
    while ($row = mysql_fetch_array($result)) { 
        $eventmonth="";
        $eventmonth = date("F Y",$row['eventdate']);

        if ($lasteventmonth != $eventmonth) {
            print "<p style='font-size: 18px;'><b>$eventmonth</b></p>";
        }
        $lasteventmonth = $eventmonth;

        showEvent($row);    
        }
    }
   ?>
........................
........................//other codes

当代码评估如下:

  

警告:mysql_num_rows():提供的参数不是第122行的C:\ Users \ Fagun \ Desktop \ UsbWebserver \ Root \ mapcal \ mapcal.php中的有效MySQL结果资源   现在没有活动。+++++++++++++++++

7 个答案:

答案 0 :(得分:3)

致电mysql_query后,请使用此身份:

if (! $result) {
    echo mysql_errno() . ": " . mysql_error(). "\n";
}

这将告诉您究竟为什么MySQL不会运行您的查询。

答案 1 :(得分:0)

是ID字符串还是int?无论哪种方式,我猜你不应该包括一个尾随的分号?

尝试更改如下... $ result = mysql_query(“SELECT *,UNIX_TIMESTAMP(eventdate)AS eventdate,
  UNIX_TIMESTAMP(throughdate)AS throughdate FROM events ORDER BY eventdate where   ID = '$ _ GET [ID]'“);

答案 2 :(得分:0)

我认为这是一个关于如何使用构建查询和连接id的问题。请尝试这样做(注意ID的连接方式):

$query = "SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,    
    UNIX_TIMESTAMP(throughdate) AS throughdate FROM events
    ORDER BY eventdate where 
    id='".$_GET[id]."'";

$result = mysql_query($query) or die(mysql_error());

您不必将其分为两部分,但是 - 这应该更容易阅读和理解。您甚至可以在运行查询之前回显查询以查看实际创建的查询,并在数据库上手动尝试。

die(mysql_error())部分会详细说明问题所在(如果不是ID问题)。

答案 3 :(得分:0)

尝试:

$result = mysql_query("SELECT   *,
                                UNIX_TIMESTAMP(eventdate) AS eventdate,    
                                UNIX_TIMESTAMP(throughdate) AS throughdate
                       FROM     events
                       ORDER BY eventdate
                       where    id= '" . intval($_GET['id']) . "'");

if($result)
{
    //Do code
}

使用intval()确保$_GET['id']是一个整数 使用if语句确保查询已正确执行。

答案 4 :(得分:0)

试试这个

 $result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,    
 UNIX_TIMESTAMP(throughdate) AS throughdate FROM events where 
 id='".$_GET['id']."' ORDER BY eventdate");

答案 5 :(得分:0)

正确引用值:

$_GET[id]应为$_GET['id']

尝试以下:

$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,    
  UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where 
  id='".$_GET['id']."');

答案 6 :(得分:0)

试试这个:

"SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate, 
    UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where 
    id='".$_GET['id'].";'"

我假设id 来自用户输入。如果是这样,则容易受到SQL注入攻击。