mysql_query() 返回 true,但 mysql_num_rows() 和 mysql_fetch_array() 给出“无效资源错误" [英] mysql_query() returns returns true, but mysql_num_rows() and mysql_fetch_array() give "not a valid resource errors
本文介绍了mysql_query() 返回 true,但 mysql_num_rows() 和 mysql_fetch_array() 给出“无效资源错误"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是有问题的代码:
来自 index.php:
From 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:
From 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
返回第一个 object
的情况在动态语言中很常见,它的计算结果为 true,但在 PHP 中 X 或 Y
的结果是总是真或假.
It is common in dynamic languages that or
returns first object
which evaluates to true, but in PHP the result of X or Y
is always true or false.
这篇关于mysql_query() 返回 true,但 mysql_num_rows() 和 mysql_fetch_array() 给出“无效资源错误"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文