2015-10-05 20 views
4

我想要做的是顯示一些數據從MySQL數據庫,如果它由用戶設置,如果它沒有設置,那麼我只是想顯示一些佔位符或「虛擬」數據。例如,如果用戶創建配置文件,他將默認獲得一些隨機或佔位符圖片作爲個人資料圖片,當他改變它時,我想從數據庫中顯示該圖片。允許說用戶描述或'關於我'部分。如果數據存在於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

這是正確的方式和它的肯定會去工作。 –

回答

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> 
+0

有趣,謝謝你的回答。 –

+0

沒問題。如果這有幫助,請給它一個upvote並將其設置爲接受的答案(當然,除非別人有更好的說法)。謝謝! – imkingdavid

+0

@imkingdavid我只是有一個問題(我會刪除此評論後)。即使佔位符是一個相當大的文本,改變順序,所以你不必使用'!'是一個好習慣?所以它看起來不像雙重否定? – FirstOne

1

你也可以做到這一點在MySQL

你總是得到的結果直接。如果用戶標識沒有發現他們從UNION

​​

這裏表返回2 SELECT

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]> 
相關問題