我想做的是显示一些数据从mysql数据库,如果它由用户设置,如果它没有设置,那么我只是想显示一些占位符或"dummy"数据。例如,如果用户创建个人资料,他将默认情况下得到一些随机或占位符图片作为个人资料图片,当他改变它,我想显示从数据库的图片。同样的道理也适用于用户描述或"关于我"部分。
这是我目前得到的
<?php
$getInfo = $con->prepare("SELECT * FROM user_info WHERE userid=:userid");
$getInfo->execute(array(':userid'=>$userID));
$data = $getInfo->fetch(PDO::FETCH_ASSOC);
$description = $data['description'];
?>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h3 class="page-title">USER DESCRIPTION</h3>
<?php if(!empty($description)) {
echo '<p>' . $description . '</p>';
} else { ?>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur incidunt, at error. Provident veritatis ratione laborum modi laudantium, quidem inventore facilis at qui blanditiis, sunt tempore labore sit, eligendi libero?</p>
<?php } ?>
</div>
</div>
</div>
所以在这里我使用!empty($description)
,但我不确定这是否是正确的方法来做到这一点,如果这总是要工作。我是mysql和php的新手,这只是为了学习目的。添加$userID
是用户登录时存在的会话
假设始终定义了$data['description'],则可以正常工作。但是,最好将逻辑和表示分开。
<?php
$getInfo = $con->prepare("SELECT * FROM user_info WHERE userid=:userid");
$getInfo->execute(array(':userid'=>$userID));
$data = $getInfo->fetch(PDO::FETCH_ASSOC);
$description = !empty($data['description']) ? $data['description'] : 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur incidunt, at error. Provident veritatis ratione laborum modi laudantium, quidem inventore facilis at qui blanditiis, sunt tempore labore sit, eligendi libero?';
?>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h3 class="page-title">USER DESCRIPTION</h3>
<p>
<?php echo $description; ?>
</p>
</div>
</div>
</div>
你也可以直接在MySQL
你总是得到一个结果。如果没有找到userid,则从UNION
返回2 SELECT。SELECT * FROM (
SELECT * FROM j WHERE userid =99999
UNION ALL
SELECT 0,'NOOOOOOOOO'
) AS c ORDER BY userid DESC LIMIT 1;
where the Table
MariaDB [tmp]> select * from j;
+--------+-------+
| userid | bame |
+--------+-------+
| 0 | 222 |
| 1 | a |
| 22 | b |
| 47 | c |
| 333 | d |
| 334 | fff |
| 335 | hhh |
| NULL | hallo |
+--------+-------+
8 rows in set (0.00 sec)
和2个样本
MariaDB [tmp]> SELECT * FROM ( SELECT * FROM j WHERE userid =1 UNION ALL SELECT 0,'NOOOOOOOOO' ) AS c ORDER BY userid DESC LIMIT 1;
+--------+------+
| userid | bame |
+--------+------+
| 1 | a |
+--------+------+
1 row in set (0.00 sec)
MariaDB [tmp]> SELECT * FROM ( SELECT * FROM j WHERE userid =99999 UNION ALL SELECT 0,'NOOOOOOOOO' ) AS c ORDER BY userid DESC LIMIT 1;
+--------+------------+
| userid | bame |
+--------+------------+
| 0 | NOOOOOOOOO |
+--------+------------+
1 row in set (0.00 sec)
MariaDB [tmp]>