我正在尝试获取一个ID和一行名为info的行,以显示用户名。
我有一个用户表:
TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT
NOT NULL,
username TEXT NOT NULL
UNIQUE,
password TEXT NOT NULL
和一个将用户ID作为FK的信息表:
TABLE infos (
infoid INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
info TEXT NOT NULL,
productid INTEGER REFERENCES product (productid)
NOT NULL,
userid INTEGER REFERENCES users (id)
NOT NULL
我设法从会话中获取用户名和用户ID:
// get username
$name = $_SESSION['username'];
$stmt = $db->prepare("SELECT id FROM users WHERE username = :name");
$stmt->execute(["name" => $name]);
$r = $stmt->fetch();
// get userid
$stmnt2 = $db->prepare("SELECT info FROM infos WHERE userid = :r");
$stmnt2->execute(["r" => $r['id']]);
我很难根据用户ID获取所有信息ID和信息。我设法得到了信息,但它错过了第一个条目,我无法获得infoid
// get info based on userid
if ($info = $stmnt2->fetch()) {
echo '<p>Your Info:</p>';
while ($info = $stmnt2->fetch()) {
echo "$info[info] </br>";
}
} else {
echo "<p>No Info</p>";
有人可以告诉我如何获得infoid和信息以表示感谢。
答案 0 :(得分:1)
替换
// get userid
$stmnt2 = $db->prepare("SELECT info FROM infos WHERE userid = :r");
$stmnt2->execute(["r" => $r['id']]);
与
// get userid
$stmnt2 = $db->prepare("SELECT info, infoid AS id FROM infos WHERE userid = :r");
$stmnt2->execute(["r" => $r['id']]);
并替换
// get info based on userid
if ($info = $stmnt2->fetch()) {
echo '<p>Your Info:</p>';
while ($info = $stmnt2->fetch()) {
echo "$info[info] </br>";
}
} else {
echo "<p>No Info</p>";
}
与
// get info based on userid
if ($info = $stmnt2->fetch()) {
echo '<p>Your Info:</p>';
do {
echo "$info[info] </br>"; //The info id is contained in the $info['id']
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
或
// get info based on userid
if ($stmnt2->num_rows()) {
echo '<p>Your Info:</p>';
while ($info = $stmnt2->fetch()){
echo "$info[info] </br>"; //The info id is contained in the $info['id']
}
} else {
echo "<p>No Info</p>";
}
我会建议你第二种方式。不要犹豫,问我任何解释。