[英]How to use if/else statement in with SQL in PHP
实际上我有以下代码:
$stmt = $pdo->prepare('SELECT id, city, date_created FROM my_table WHERE city = :city ORDER BY date_created DESC LIMIT 1');
$stmt->execute(array(':city' => $city));
我试图解释我想做什么:
检查是否在列city
包含all
行。
如果是这样,请检查date_created
中此行的日期是否比上述查询的最新条目中的日期新。 如果是这样,请选择此行,否则请选择下面查询的最新条目。
我希望你理解我想做什么。 不幸的是,我对SQL中的if / else语句不熟悉。
有谁能够帮助我?
我认为这可以简化。
看起来您应该能够只选择城市为您的参数或“全部”的行,按date_created
降序排序,就像您已经是的那样,并采用第一行。
$sql = "SELECT id, city FROM news
WHERE city IN(:city, 'all')
ORDER BY date_created DESC LIMIT 1";
由于您知道查询将仅返回一行,因此可以只使用fetch
而不是fetchAll
来消除不必要的外部数组。
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':city' => $city));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
原因我对SQL中的if / else语句不熟悉,但是在PHP中,我做了以下工作:
<?php
$stmt = $pdo->prepare('SELECT id, city, date_created FROM news WHERE city = :city ORDER BY date_created DESC LIMIT 1');
$stmt->execute(array(':city' => $city));
$results = $stmt->fetchAll();
foreach( $results as $row ) {
$date_city = $row['date_created'];
}
$stmt = $pdo->prepare('SELECT id, city, date_created FROM my_table WHERE city = "all" ORDER BY date_created DESC LIMIT 1');
$stmt->execute();
$results = $stmt->fetchAll();
foreach( $results as $row ) {
$date_all = $row['date_created'];
}
if ($date_all > $date_city) {
$stmt = $pdo->prepare('SELECT id, city, date_created FROM my_table WHERE city = "all" ORDER BY date_created DESC LIMIT 1');
$stmt->execute(array(':city' => $city));
} else {
$stmt = $pdo->prepare('SELECT id, city, date_created FROM my_table WHERE city = :city ORDER BY date_created DESC LIMIT 1');
$stmt->execute(array(':city' => $city));
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.