如何获得此代码的输出。有时它显示输出,有时它不显示?

时间:2013-08-18 17:15:15

标签: php html mysql sql arrays

    <?php
include 'config.php';
$tid = $_GET['tid'];
$sql="SELECT FROM topics where tid='$tid'";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
?> 
<div class="topics"><font size="4"><?php echo $rows['title']; ?></font></div><div class="tdm"><br/><center><img src="http://appricart.com/test/img/<?php echo $rows['photo']; ?>" height="100" width="100"/><br/>
<small><?php echo $rows['message']; ?></small></div>
<?php
}
include 'foot.php';
?>

有时此代码有效,但有时请不要帮我解决这个问题。

显示此错误

mysql_fetch_array() expects parameter 1 to be resource

2 个答案:

答案 0 :(得分:1)

您没有进行任何错误检查以防止这种情况发生。当您的MySQL查询无法执行时,会导致此错误。您有mysql_query()语句,结果存储在变量中。稍后,您在mysql_fetch_array()语句中使用该变量。

如果mysql_query失败,则返回FALSE这是一个布尔值。 mysql_fetch_array期望它成为一种资源。

要解决此问题并了解查询失败的原因,请使用mysql_error()函数。

$result = mysql_query($sql);
if (!$result) { 
    die('Query failed because: ' . mysql_error());
}
else {
//proceed
}

在这种情况下,您没有像Sean上面提到的那样从数据库中选择任何内容。

尝试以下方法:

$sql = "SELECT * FROM topics where tid='$tid'";

或者

$sql = "SELECT topics FROM topics where tid='" . $tid . "'";

Also, please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

答案 1 :(得分:0)

 <?php
include 'config.php';
$tid = $_GET['tid'];
$sql="SELECT FROM topics where tid='$tid'"; // here is the error
$result=mysql_query($sql);

您没有从表格主题中选择任何内容。因此它显示错误..

$sql="SELECT * FROM topics where tid='$tid'"; // this would be better

了解更多信息,请访问mysql_fetch_array