我对 PHP 还是个新手,还没有发展出知道如何在预料到大多数错误时修复它们的知识。我在连接到我刚刚创建的数据库时遇到问题。我正在从一本书中学习这个例子。浏览器不断返回结果:“警告: mysql_fetch_array() 期望参数 1 为资源, bool 值在:'文件路径'”中给出。我假设 $result 有问题,但请查看它。我的代码如下所示:
<?php
// Open a MySQL connection
$link = mysql_connect('xxx', 'xxx', 'xxx');
if(!$link) {
die('Connection failed' . mysql_error());
}
// Select the database to work with
$db = mysql_select_db('test');
if(!$db) {
die('Selected database unavailable: ' . mysql_error());
}
// Create and execute a MySQL query
$sql = "SELECT artist_name FROM artists";
$result = mysql_query($sql);
// Loop through the returned data and output it
while($row = mysql_fetch_array($result)) {
printf("Artist: %s<br />", $row['artist_name']);
}
// Free the memory associated with the query
mysql_free_result($result);
// Close the connection
mysql_close($link);
?>
最佳答案
万一 mysql_query 失败,它返回 false,一个 bool 值。当您将其传递给 mysql_fetch_array 函数(需要 mysql 结果对象)时,我们会收到此错误。确保您使用的查询将获取一些结果,或者您使用的是正确的列名。
您应该按照其他人的建议切换到使用 mysqli 或 PDO。
关于php - MySQL 数据库连接与 PHP MySQL 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633524/