我无法弄清楚为什么会出现这样的问题。显示的错误 mysqli_fetch_assoc()要求参数1为mysqli_result 。 我的代码是这样的。我不知道哪一个是错的。
看看我的con.php。
<?php
$conn = mysqli_connect('localhost', 'username', 'password');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
这是我的page.php
<?php
include 'con.php';
$link = mysqli_connect('localhost', 'username', 'password', 'username') or die("Error " . mysqli_error($link));
$query = " SELECT thread_id, thread_name, thread_date
FROM forum_thread
ORDER BY thread_date";
$result = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($result)) {
$thread_id = $row ['thread_id'];
$thread_name = $row['thread_name'];
$thread_date = $row['thread_date'];
echo "$thread_id, $thread_name, $thread_date";
有什么想法吗?感谢您的任何答案。干杯!
答案 0 :(得分:1)
我想我明白了:
更改$result = mysqli_query($link,$query);
到$result = mysqli_query($conn,$query);
,因为$conn
是您的数据库连接,而不是$link
根据您在上面发布的内容
<?php
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
并删除:
$link = mysqli_connect('localhost', 'username', 'password', 'username') or die("Error " . mysqli_error($link));
因为您已经使用include 'con.php';
或者这样:
<?php
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name') or die("Error " . mysqli_error($conn));
$query = " SELECT thread_id, thread_name, thread_date
FROM forum_thread
ORDER BY thread_date";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result)) {
$thread_id = $row ['thread_id'];
$thread_name = $row['thread_name'];
$thread_date = $row['thread_date'];
echo "$thread_id, $thread_name, $thread_date";
答案 1 :(得分:0)
错误消息表明查询由于某种原因确实失败了。而不是仅使用$result
测试来查看它是否有效,如果没有将错误输出到屏幕或日志文件:
if ($result) {
// continue processing $result
}
else {
echo mysqli_error($link);
}
编辑: mysqli_connect中的第4个参数应该是数据库的名称,“abc”或其他。
答案 2 :(得分:0)
尝试使用以下代码
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli- >connect_error;
}
当您尝试获取连接对象本身时,如果出现问题,您可以识别问题。