プロが教える店舗&オフィスのセキュリティ対策術

下記のコードでは、sprintfにクエリを書いていますが、その中でも一部の行だけifを使って条件分岐で切り替えることができないものかと思いました? もちろん下記のコードでは動きませんが、イメージとしては、このような感じです。


try{

$sql = sprintf('SELECT '
. 'SQL_CALC_FOUND_ROWS %1$s.ID,'
. '%1$s.ID, '
. '%1$s.post_author,'
. '%1$s.post_title, '
. '%1$s.post_date, '
. '%1$s.post_status,'
. '(SELECT %2$s.name FROM %2$s WHERE %1$s.category = %2$s.term_id) AS category , '
. '(SELECT %2$s.name FROM %2$s WHERE %1$s.category_child = %2$s.term_id) AS category_child , '
. '%1$s.post_content , '
. '(SELECT count(%3$s.post_id) FROM %3$s WHERE %1$s.ID = %3$s.post_id) AS b_count, '
. '(SELECT count(%4$s.post_id) FROM %4$s WHERE %1$s.ID = %4$s.post_id) AS l_count, '
. '(SELECT count(%5$s.comment_ID) FROM %5$s WHERE %1$s.ID = %5$s.comment_post_ID) AS c_count '

if(isset($ID)){
. 'FROM %1$s WHERE %1$s.post_author = :post_author AND %1$s.post_status = 2 ORDER BY %1$s.post_date DESC LIMIT %6$s, %7$s', $this->posts, $this->category,$this->bookmark,$this->like,$this->comments,$limit, $offset);
}elseif(isset($ID) AND $ID==$user_id){
. 'FROM %1$s WHERE %1$s.post_author = :post_author AND %1$s.post_status = 3 ORDER BY %1$s.post_date DESC LIMIT %6$s, %7$s', $this->posts, $this->category,$this->bookmark,$this->like,$this->comments,$limit, $offset);
}else{
. 'FROM %1$s WHERE %1$s.post_author = :post_author AND %1$s.post_status = 1 ORDER BY %1$s.post_date DESC LIMIT %6$s, %7$s', $this->posts, $this->category,$this->bookmark,$this->like,$this->comments,$limit, $offset);
}


$stmt = $this->db->prepare($sql);
$stmt->bindValue('post_author', $user_id);
$stmt->execute();
$data['all'] = $stmt->fetchAll();

A 回答 (1件)

三項演算子でがんばってみては?



$flg=true;
$str="hogehoge".($flg?" fugafuga":" piyopiyo")." hogera";
print $str;

※ただし三項演算子で条件が3つになるとグルーピングを明確にしないといけませんが・・・
    • good
    • 0
この回答へのお礼

ありがとうこざいます。
三項演算子はこのような使い方もできるのですね。知りませんでした。
三項演算子はたまに見かけるものの、自分に限っては、ifばかりで分岐していたので勉強になります。

お礼日時:2017/05/15 23:22

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!