php - mysql_query() 返回返回 true,但 mysql_num_rows() 和 mysql_fetch_array() 给出“不是有效资源错误

标签 php mysql

这里是有问题的代码:

来自 index.php:

require_once('includes/DbConnector.php');

// Create an object (instance) of the DbConnector
$connector = new DbConnector();

// Execute the query to retrieve articles
$query1 = "SELECT id, title FROM articles ORDER BY id DESC LIMIT 0,5";
$result = $connector->query($query1);

echo "vardump1:";
var_dump($result);
echo "\n";

/*(!line 17!)*/ echo "Number of rows in the result of the query:".mysql_num_rows($result)."\n";
// Get an array containing the results.
// Loop for each item in that array


while ($row = $connector->fetchArray($result)){

echo '<p> <a href="viewArticle.php?id='.$row['id'].'">';
echo $row['title'];
echo '</a> </p>';

来自 dbconnector.php:

$settings = SystemComponent::getSettings();

// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];

// Connect to the database
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));

} //end constructor

//*** Function: query, Purpose: Execute a database query ***
function query($query) {

echo "Query Statement: ".$query."\n";

$this->theQuery = $query;

return mysql_query($query, $this->link) or die(mysql_error());

}

//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {

echo "<|";
var_dump($result);
echo "|> \n";

/*(!line 50!)*/$res= mysql_fetch_array($result) or die(mysql_error());

echo $res['id']."-".$res['title']."-".$res['imagelink']."-".$res['text'];

return $res;
}

输出:

Query Statement: SELECT id, title FROM articles ORDER BY id DESC LIMIT 0,5 vardump1:bool(true) 
PHP Error Message

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /*path to*/index.php on line 17

Number of rows in the result of the query: <|bool(true) |> 

PHP 错误信息

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /*path to*/DbConnector.php on line 50

最佳答案

您的问题出在下一行:

return mysql_query($query, $this->link) or die(mysql_error())

应该这样写:

$result = mysql_query($query, $this->link);
if(!$result) die(mysql_error());
return $result;

在动态语言中,or 返回第一个评估为 true 的 object 是很常见的,但在 PHP 中,X 或 Y 的结果是始终为 truefalse

关于php - mysql_query() 返回返回 true,但 mysql_num_rows() 和 mysql_fetch_array() 给出“不是有效资源错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3009035/

相关文章:

mysql - 在索引上覆盖 SELECT 给出了 using where;使用索引;而不是只使用索引;

mysql - 尝试使用存储过程访问三个表但只接收一行

PHP 将值插入两个表并将这些表中的键插入链接表

php - 在php中按值查找多维关联数组的键

PHP 正则表达式捕获第一个模式及其后的所有内容,即使它重复。

php - 我的登录页面上的数据丢失?

php - 从 MySQL 到 PHP 页面选择数据时遇到问题

PHP fatal error : Constant expression contains invalid operations

php - LIKE MYSQL 只得到 1 个结果

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数 1 是资源