我写了这段代码:
<div class="col-md-4" id="message_widget">
<div class="card">
<div class="card-header">
Latest messages
<?php
$query = $database->getConnection()->prepare('SELECT count(id) FROM messages WHERE messageRead = 0 AND messageTrash = 0 AND userId = ?');
$query->bind_param('i', $id);
if($database->getData($query)[0] > 0){
$messageNumber = $database->getData($query)[0];
echo "<span class='badge badge-danger badge-pill pull-right'>$messageNumber</span>";
}
?>
</div>
<div class="card-block">
<table class='table' id="table">
<?php
$messageStatement = $database->getConnection()->prepare("SELECT * FROM messages WHERE userId=? AND messageDeleted = 0 AND messageTrash = 0 AND messageRead= 0 ORDER BY time_added LIMIT 3");
$messageStatement->bind_param('i', $id );
$latestMessages= $database->getDataAsArray($messageStatement);
if(!$latestMessages){
echo "<tr><td colspan='2' style='text-align: center'>No new unread messages</td> </tr>";
}
foreach($latestMessages as $message){
$time_added = $message['time_added'];
$number = $message['id'];
$subject = $message['subject'];
echo "<tr>
<td><a href='showMessage.php?id=$number'>$subject</a></td>
<td>$time_added</td>
</tr>";
}
?>
</table>
</div>
</div>
</div>
如果某个条件为真,我只想在页面上构建这个col-md-6。在其他每种情况下都不应该构建它。 JavaScript不是一个选项,这给了我不想要的奇怪效果(构建页面然后添加或删除项目)
我知道当代码只有HTML时,如果条件为真,我可以通过php轻松回显代码,但是当条件为真时如何创建上面的代码?
答案 0 :(得分:1)
使用<?php if(): ?>---<?php endif; ?>
尝试此操作
它被称为替代语法 see this
<?php if(condition == true): ?>
<div class="col-md-4" id="message_widget">
<div class="card">
<div class="card-header">
Latest messages
<?php
$query = $database->getConnection()->prepare('SELECT count(id) FROM messages WHERE messageRead = 0 AND messageTrash = 0 AND userId = ?');
$query->bind_param('i', $id);
if($database->getData($query)[0] > 0){
$messageNumber = $database->getData($query)[0];
echo "<span class='badge badge-danger badge-pill pull-right'>$messageNumber</span>";
}
?>
</div>
<div class="card-block">
<table class='table' id="table">
<?php
$messageStatement = $database->getConnection()->prepare("SELECT * FROM messages WHERE userId=? AND messageDeleted = 0 AND messageTrash = 0 AND messageRead= 0 ORDER BY time_added LIMIT 3");
$messageStatement->bind_param('i', $id );
$latestMessages= $database->getDataAsArray($messageStatement);
if(!$latestMessages){
echo "<tr><td colspan='2' style='text-align: center'>No new unread messages</td> </tr>";
}
foreach($latestMessages as $message){
$time_added = $message['time_added'];
$number = $message['id'];
$subject = $message['subject'];
echo "<tr>
<td><a href='showMessage.php?id=$number'>$subject</a></td>
<td>$time_added</td>
</tr>";
}
?>
</table>
</div>
</div>
</div>
<?php endif; ?>
&#13;