![](/img/trans.png)
[英]How can I get a specific value from a database and compare it based on that value with PHP?
[英]How can I get a value by it self using php from a database?
我正在尝试自行访问firstname
。 我将以下代码放在一起:
<?php $sql = "SELECT firstname, lastname FROM guests WHERE option = $option"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "You Are " . $row["firstname"]. " " . $row["lastname"]. "<br>"; ?>
它给我You are Bob Testing.
我需要将它们转换为自变量,以便可以在任何地方使用它们。 像$row["firstname"] = $firstname;
这样我就可以echo $firstname;
但是如果我使用$row["firstname"] = $firstname;
它将无法正常工作$row["firstname"] = $firstname;
我认为问题在于我如何形成结果$result = mysqli_query($conn, $sql);
我可以在这里说些什么,然后再用$row["firstname"] = $firstname;
并使用像echo $firstname;
? 谢谢。
首先,如果这是您的实际代码,则缺少一些右花括号。
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You Are " . $row["firstname"]. " " . $row["lastname"]. "<br>";
} // this one was missing
} // as was this one
现在,将变量分配给行,而不是相反。
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$first = $row["firstname"];
$last = $row["lastname"];
}
echo "You are " . $first . " " . $last . "<br>";
}
但是,上面仅回显了一行,因此,您需要将echo放置在while
循环内,以便回显表中的所有行:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$first = $row["firstname"];
$last = $row["lastname"];
echo "You are " . $first . " " . $last . "<br>";
}
}
关于此事,虽然WHERE option = $option";
如果$option
是字符串,则需要用引号引起来:
WHERE option = '$option'";
否则,MySQL会将其视为语法错误。 检查查询中的错误:
这也很容易发生SQL注入,因此最好使用准备好的语句。
看到您可能不是使用MySQL的新手,那么最好了解一下如何防止SQL注入。 这是一篇关于Stack的好文章:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.