如何将中的if/else语句与PHP中的SQL一起使用
实际上,我有以下代码:如何将中的if/else语句与PHP中的SQL一起使用,php,mysql,sql,if-statement,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)); 我试图解释我想做什么: 检查是否有一行包含城市中的所有列 如果是,请检查date_created中此行的日期是否比上面查询的最
$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));
我试图解释我想做什么:
检查是否有一行包含城市中的所有列
如果是,请检查date_created中此行的日期是否比上面查询的最新条目中的日期新。如果是,请选择此行,否则请选择下面查询的最新条目
我希望你明白我想做什么。不幸的是,我不熟悉SQL中的if/else语句
有人能帮我吗?因为我不熟悉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));
}
?>
我认为这可以简化 看起来您应该能够只选择城市是您的参数或“全部”的行,按日期按降序创建,并选择第一行
$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);
然后用准备好的语句查看下面或PDO方法:-很可能是这个问题的副本。步骤1:向where子句添加and value='all'。。。或者一个或,取决于你想要寻找什么;问题太宽泛了。您发布的答案我觉得应该是您问题的一部分此声明$stmt=$pdo->准备“从新闻中选择id,城市=所有订单的日期_创建描述限制1”$stmt->execute$结果=$stmt->fetchAll;可以减少到$stmt=$pdo->query'SELECT id,city FROM news,其中city=all ORDER BY date_created DESC LIMIT 1'->fetchall;foreach$stmt as$row看起来不应该这样,因为不应该设置$row['date_created'],因为您在查询中只选择id和city。