如果mysql数据库中存在数据,则使用占位符数据

时间:2015-10-05 19:50:15

标签: php mysql pdo

我想要做的是显示mysql数据库中的一些数据,如果它由用户设置,如果没有设置,那么我只想显示一些占位符或“虚拟”数据。例如,如果用户创建配置文件,他将默认获得一些随机或占位符图片作为配置文件图片,当他更改它时,我想从数据库中显示该图片。同样可以说是用户描述或“关于我”部分。

这是我到目前为止所得到的

<?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的新手,这只是为了学习puropses。只是添加$userID是用户登录时存在的会话。

2 个答案:

答案 0 :(得分:2)

假设$ 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>

答案 1 :(得分:1)

您也可以直接在MySQL中执行

你总会得到一个结果。如果未找到用户标识,则返回UNION的2 SELECT

SELECT * FROM (
  SELECT * FROM j WHERE userid =99999
  UNION ALL
  SELECT 0,'NOOOOOOOOO'
  ) AS c ORDER BY userid DESC LIMIT 1;

此处的表格

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]>