如何在PHP中使用if / else语句和SQL

时间:2017-03-15 16:36:23

标签: php mysql sql if-statement

其实我有以下代码:

$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));

我试着解释一下我想做什么:

  1. 检查列all中是否有包含city的行。

  2. 如果是,请检查date_created中此行的日期是否比上述查询的最新条目中的日期更新。如果是,请选择此行,否则请选择下面查询的最新条目。

  3. 我希望你明白我想做什么。不幸的是,我不熟悉SQL中的if / else语句。

    有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

我认为这可以简化。

看起来您应该只能选择城市是您的参数或“全部”的行,按照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);

答案 1 :(得分:0)

因为我不熟悉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));
}
?>