我正在使用这个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查询结果包含我最近修复过的拼写错误,并且我已经在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
我做错了什么?
答案 0 :(得分:1)
你正在使用过时的函数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();
}
?>
答案 1 :(得分:1)
<%#= Preferably, you should initialize '@contact = Contact.new' in your action and form should be unchanged %>
<%= form_for(Contact.new) do |f| %>
这应该有效。如果没有向我报告
答案 2 :(得分:1)
您正在将Mysqli与Mysql混合使用。
使用Mysqli方法查询:
$res = $db_handle->query($SQL);
while ($row = $res->fetch_assoc()) {
// do stuff
}
这里的文档: http://php.net/manual/en/mysqli.quickstart.statements.php