我写了这段代码:
<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回显代码,但是当条件为真时,如何创建上述代码?
最佳答案
尝试使用<?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; ?>