【问题标题】:how to get output of this code. sometimes it shows output and sometime it doesnot?如何获取此代码的输出。有时它显示输出,有时它不显示?
【发布时间】:2013-08-20 12:49:36
【问题描述】:
    <?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

【问题讨论】:

  • 当您的查询出现错误时,您仍然使用$result 调用mysql_fetch_array,这不是合法资源。您还应该注意到 mysql 扩展已被弃用。您应该使用更现代的,例如 MysqliPDO Mysql
  • 我假设您的查询是复制/粘贴错误,即。 SELECT title, photo, message FROM ...SELECT * FROM ... 而不是 SELECT FROM ...。此外,您可以通过在查询中直接使用 $_GET 值而不转义它来打开 SQL 注入。

标签: php html mysql sql arrays


【解决方案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
}

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

尝试以下方法:

$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

【讨论】:

    【解决方案2】:
     <?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

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多