用户名:
密 码: 记住
您当前的位置:首页 > 网络编程 > php教程

Warning: mysql_fetch_assoc() expects parameter 1 to be resource

时间:2015-01-23  来源:西部数据  作者:西部数据

今天学习php的时候遇到了这个错误:Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:xampphtdocsmyblogindex.php on line 15

源代码是:

  1. <?php 
  2.  $sql="select entries.*,categories.cat from entries,categorie where entries.cat_id=categories.id order by dateposted desc limit 1;"
  3.  $result=mysql_query($sql); 
  4.       $row=mysql_fetch_assoc($result); 
  5.       echo "<h2><a href='viewentry.php?id=" . $row['id'] . "'>" . $row['subject'] . "</a></h2><br/>";  
  6.       echo "<i> in <a href='viewcat.php?id=" . $row['cat_id'] . "'>" . $row['cat'] . "</a> - Posted on " . date("D js F Y g.iA",strtotime($row['dateposted'])) . "</i>"
  7.     echo "<p>"
  8.     echo nl2br($row['body']); 
  9.     echo "</p>"

百度了一下,找到了解决办法!他出错的原因是因为数据库中没有数据导致musql_fetch_assoc()函数返回值为false,所以下面的$row['']使用就出错了,所以在使用mysql_fetch_assoc() 函数的时候先对$result做判断!

  1. <?php 
  2.  $sql="select entries.*,categories.cat from entries,categorie where entries.cat_id=categories.id order by dateposted desc limit 1;"
  3.  $result=mysql_query($sql); 
  4.  if($result){ 
  5.       $row=mysql_fetch_assoc($result); 
  6.       echo "<h2><a href='viewentry.php?id=" . $row['id'] . "'>" . $row['subject'] . "</a></h2><br/>";  
  7.       echo "<i> in <a href='viewcat.php?id=" . $row['cat_id'] . "'>" . $row['cat'] . "</a> - Posted on " . date("D js F Y g.iA",strtotime($row['dateposted'])) . "</i>"
  8.     echo "<p>"
  9.     echo nl2br($row['body']); 
  10.     echo "</p>"
  11.  } 
  12.  else
  13.    echo "没有文章"
  14.  } 
  15. ?> 

这样就不会报错了,注释:mysql_fetch_assoc() 函数

定义和用法:mysql_fetch_assoc() 函数从结果集中取得一行作为关联数组,返回根据从结果集取得的行生成的关联数组,如果没有更多行,则返回 false。

语法:mysql_fetch_assoc(data)

data 必需,要使用的数据指针。该数据指针是从 mysql_query() 返回的结果。

提示和注释

注释:mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二个可选参数 MYSQL_ASSOC 完全相同。它仅仅返回关联数组。这也是 mysql_fetch_array() 初始的工作方式。

提示:如果在关联索引之外还需要数字索引,用 mysql_fetch_array()。

注释:本函数返回的字段名是区分大小写的。

来顶一下
返回首页
返回首页
推荐资讯
WiFi太不安全:7岁女孩11分钟内入侵公共网络 WiFi太不安全:7岁女孩11分钟内入侵近期刚刚发布研究说WiFi网络能获得人们手机里多少私人信息,
不服跑个分?人工智能也出现“刷分”乱象 不服跑个分?人工智能也出现“刷分2014年,人工智能领域突然爆发,成为了科研和科技创业的热门
相关文章
栏目更新
栏目热门