每当我使用:while($x = mysqli_fetch_array($y))
然后echo $x
时,它将返回除第一行之外的所有内容。
表格:
的 forum.users
forum.forums
这是我的代码:
<?php
session_start();
$con = new mysqli("localhost", "root", "", "forum");
if(!isset($_SESSION["online"])==1) {
$_SESSION["offline"] = "true";
}
$username = $_SESSION["online"];
$u_query = "SELECT * FROM forum.users WHERE users.username = '".$username."'";
$u_result = $con -> query($u_query);
$u_row = mysqli_fetch_array($u_result);
if(isset($_POST["logout"])) {
session_unset();
session_destroy();
header("Location: login.php");
}
$f_search = "SELECT * FROM forum.forums WHERE user_id = '".$u_row['user_id']."'";
$f_result = $con -> query($f_search);
$f_row = mysqli_fetch_array($f_result);
?>
<html>
<head>
<title>Home</title>
<charset = "UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="header">
<div id="user">
<img src="<?php echo $u_row['image']; ?>" id="user-image">
<?php echo $u_row["username"]; ?>
<form method="post">
<input type="submit" name="logout" value="sign out">
</form>
</div>
</div>
<?php if(mysqli_num_rows($f_result)>= 0) { ?>
<div>
<div>Your forums:</div><table><tr>
<?php while($f_row = mysqli_fetch_array($f_result)) { ?>
<td><a href="forum.php?forumid=<?php echo $f_row['forum_id']; ?>"><?php echo $f_row["name"]; ?></a></td>
<td></td>
<?php } ?>
</tr></table>
</div>
<?php } ?>
</body>
</html>
为什么不返回第一行?
答案 0 :(得分:3)
调用mysqli_fetch_array
获取行并前进光标。所以你的第一个
$f_row = mysqli_fetch_array($f_result);
有第一行。然后
while($f_row = mysqli_fetch_array($f_result)) {
前进到第二行,并循环显示所有其他结果。
因此,要么摆脱$f_row = mysqli_fetch_array($f_result);
之外的while
,要么输出while
之前的内容。它看起来不像你正在使用那个阵列所以我只是删除它。
此外:
$username = $_SESSION["online"];
$u_query = "SELECT * FROM forum.users WHERE users.username = '".$username."'";
对SQL注入开放。您应该使用预准备语句并参数化查询。 http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
答案 1 :(得分:0)
删除$f_row = mysqli_fetch_array($f_result);
通过在脚本的早期调用它,你正在推进指针+1。然后在你的while($f_row = mysqli_fetch_array($f_result))
中,你实际上从第二行开始。
$f_search = "SELECT * FROM forum.forums WHERE user_id = '".$u_row['user_id']."'";
$f_result = $con -> query($f_search);
$f_row = mysqli_fetch_array($f_result); // <---- remove this line