我正在使用这段PHP代码学习数据库和PHP,尽管我收到了错误消息:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 20
起初,SQL查询包含我最近修复的I拼写错误,并且我直接在PHPMyAdmin中运行了SQL查询,在那里它可以正常工作。使用mysql_error()
行我找不到任何合理的提示。
以下是代码的其余部分:
<!DOCTYPE html>
<html>
<body>
<?php
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "localhost";
$db_handle = new mysqli($server, $user_name, $password);
$db_found = $db_handle->select_db($database);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
$db_handle->close();
} else {
print "Database NOT found";
$db_handle->close();
}
?>
</body>
</html>
进行
if ($result) {
}
返回false
我做错了什么
您使用的是过时的函数mysql_query。使用mysqli_query、mysqli_fetch_assoc,您的代码应该看起来像这个
<?php
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "localhost";
$db_handle = new mysqli($server, $user_name, $password);
$db_found = $db_handle->select_db($database);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysqli_query($db_found,$SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
$db_handle->close();
} else {
print "Database NOT found";
$db_handle->close();
}
?>
<!DOCTYPE html>
<html>
<body>
<?php
class Connection {
protected $host = "localhost";
protected $dbname = "addressbook";
protected $user = "root";
protected $pass = "";
protected $conn;
function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->user, $this->pass);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
public function closeConnection() {
$this->conn = null;
}
}
class querys extends Connection{
public function adres_book{
$sql = "SELECT * FROM tb_address_book";
$sql = $this->conn->prepare($sql);
$sql->execute();
return $sql->fetchAll();
}
}
$conn = new Connection();
$query = new querys();
?>
On the php file:
<?php
Foreach($query->adres_book() as $db_field){
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
?>
</body>
</html>
这应该行得通。如果没有向我报告
您正在将Mysqli与Mysql混合。
使用Mysqli方法查询:
$res = $db_handle->query($SQL);
while ($row = $res->fetch_assoc()) {
// do stuff
}
以下是文档:http://php.net/manual/en/mysqli.quickstart.statements.php