我现在用PHP代码遇到了一些问题。首先,我有一个MySQL数据库,我存储了一些数据,我正在检索这些数据并使用PHP在页面上显示它。这是代码,所以我可以更好地描述我的问题:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM sample";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<span class='infoTitle'>Now:</span>".$row["now"]."<br>".
"<span class='infoTitle'>Status:</span> ".$row["status"]."<br>";
if (trim($row["now"] == 1)) {echo "Yes";} if(trim($row["now"] == 0)) {echo "";}
if ($row["status"] == 3) {echo "Open";} if($row["status"] == 2) {echo "Closed";}
}
}
else {
echo '<h2 class="noInfo">Whoops! Looks like there is currently no information available.</h2>';
}
$conn->close();
?>
所以我遇到的问题是条件语句。我有隐藏在php页面中的输入信息来自哪里,它会将隐藏字段的值输入MySQL。那么代码当前在我的浏览器中显示的是这样的:
Now: 1
Status: 3
YesOpen
但我试图让它做的就是这个
Now: Yes
Status: Open
答案 0 :(得分:1)
您的代码中的错误很少:
trim($row["now"] == 1)
- 它应该是trim($row["now"]) == 1
等等(否则你执行修剪布尔值,因为$row["now"] == 1
将首先评估)echo
,然后检查并显示THEN'status'和'now',它对第一次回显没有影响,因为在下一次迭代中读取新行并且放置未格式化的值进入'第一回声'只需将循环更改为类似的内容:
while ($row = $result->fetch_assoc()) {
if (intval($row["now"]) == 1) {
$now = "Yes";
} else {
$now = "";
}
if ($row["status"] == 3) {
$status = "Open";
} else if($row["status"] == 2) {
$status = "Closed";
} else {
$status = '';
}
echo "<span class='infoTitle'>Now:</span>".$now."<br><span class='infoTitle'>Status:</span> ".$status."<br>";
}
然后应该没事。
答案 1 :(得分:0)
这对你有意义吗?在我尝试输出行之前,我已经建立了值
// output data of each row
while($row = $result->fetch_assoc()) {
$firstvar = "";
$secondvar = "";
if (trim($row['now']) == 1)
{$firstvar = "Yes";}
if(trim($row['now']) == 0)
{$firstvar = "";}
if ($row['status'] == 3)
{$secondvar = "Open";}
if($row['status'] == 2)
{$secondvar = "Closed";}
echo "<span class='infoTitle'>Now: </span>" . $firstvar . "<br>";
echo "<span class='infoTitle'>Status: </span> " . $secondvar . "<br>";