以下是相关代码:
来自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
答案 0 :(得分:5)
你的问题已经出现了问题:
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 or Y
的结果始终为 true 或<强>假强>
答案 1 :(得分:0)
正如您可以从手册中学到的,mysql_query返回值类型不是布尔值而是资源 你的代码转换它的东西
答案 2 :(得分:0)
同意上述内容,您的mysql_query存在问题。它永远不应该返回True。无论是虚假还是资源。
重构:mysql_query($ query,$ this-&gt; link)或die(mysql_error())
在查询后回显mysqlerror()并查看错误消息是什么。您可能没有有效的连接。