| 
       今天学习php的时候遇到了这个错误:Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:xampphtdocsmyblogindex.php on line 15 
源代码是: 
	
	- <?php 
 
	-  $sql="select entries.*,categories.cat from entries,categorie where entries.cat_id=categories.id order by dateposted desc limit 1;"; 
 
	-  $result=mysql_query($sql); 
 
	-       $row=mysql_fetch_assoc($result); 
 
	-       echo "<h2><a href='viewentry.php?id=" . $row['id'] . "'>" . $row['subject'] . "</a></h2><br/>";  
 
	-       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>"; 
 
	-     echo "<p>"; 
 
	-     echo nl2br($row['body']); 
 
	-     echo "</p>"; 
 
	 
 
百度了一下,找到了解决办法!他出错的原因是因为数据库中没有数据导致musql_fetch_assoc()函数返回值为false,所以下面的$row['']使用就出错了,所以在使用mysql_fetch_assoc() 函数的时候先对$result做判断! 
	
	- <?php 
 
	-  $sql="select entries.*,categories.cat from entries,categorie where entries.cat_id=categories.id order by dateposted desc limit 1;"; 
 
	-  $result=mysql_query($sql); 
 
	-  if($result){ 
 
	-       $row=mysql_fetch_assoc($result); 
 
	-       echo "<h2><a href='viewentry.php?id=" . $row['id'] . "'>" . $row['subject'] . "</a></h2><br/>";  
 
	-       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>"; 
 
	-     echo "<p>"; 
 
	-     echo nl2br($row['body']); 
 
	-     echo "</p>"; 
 
	-  } 
 
	-  else{ 
 
	-    echo "没有文章"; 
 
	-  } 
 
	- ?> 
 
	 
 
这样就不会报错了,注释: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()。 
注释:本函数返回的字段名是区分大小写的。 
      
      (责任编辑:admin) |