mysql_query()返回true,但mysql_num_rows()和mysql_fetch_array()给出"没有有效的资源错误

zla*_*012 5 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>';
Run Code Online (Sandbox Code Playgroud)

从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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

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) |> 
Run Code Online (Sandbox Code Playgroud)

PHP错误消息

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

Ski*_*Ski 5

你的问题在于:

return mysql_query($query, $this->link) or die(mysql_error())
Run Code Online (Sandbox Code Playgroud)

它应该是这样写的:

$result = mysql_query($query, $this->link);
if(!$result) die(mysql_error());
return $result;
Run Code Online (Sandbox Code Playgroud)

在动态语言中常见的是or首先返回object,其值为true,但在PHP中,结果X or Y始终为truefalse.


You*_*nse 0

从手册中可以了解到,mysql_query返回值类型不是boolean而是resource。
您的代码中的某些内容将其转换