gpt4 book ai didi

php - 使用 PDO 的 SELECT 查询失败,在 phpMyAdmin 中有效

转载 作者:行者123 更新时间:2023-11-29 06:05:35 24 4
gpt4 key购买 nike

数据库

start                  end
2012-07-21 15:40:00 2012-07-28 21:00:00
2012-07-23 20:00:00 2012-07-27 13:00:00

这是我通过 phpMyAdmin 运行并返回正确的行

SELECT * 
FROM `events`
WHERE "2012-07-25 15:40"
BETWEEN START AND END

但是在我下面发布的 php 代码中我无法得到任何结果。 (表格提交的所有数据均100%发布)。我错过了什么?

$question= 'SELECT * FROM events WHERE ';

$hasTime = false;
if(!empty($time)) { // @note better validation here
$hasTime = true;
$question .= 'WHERE time=:time BETWEEN start AND end';
}
$hasCity = false;
if(!empty($city)) { // @note better validation here
$hasCity = true;
$question .= 'AND city=:city ';
}
$hasType = false;
if(!empty($type)) { // @note better validation here
$hasType = true;
$question .= 'AND type=:type';
}

$query = $db->prepare($question);

if($hasTime)
$query->bindValue(":time", $time, PDO::PARAM_INT);
if($hasCity)
$query->bindValue(":city", $city, PDO::PARAM_INT);
if($hasType)
$query->bindValue(":type", $type, PDO::PARAM_INT);

$query->execute();

最佳答案

$question= 'SELECT * FROM events WHERE ';

$hasTime = false;
if(!empty($time)) { // @note better validation here
$hasTime = true;
$question .= 'WHERE time=:time BETWEEN start AND end';
}

您的查询中将出现两次 WHERE,这是一个语法错误。改变

$question .= 'WHERE time=:time BETWEEN start AND end';

$question .= 'time=:time BETWEEN start AND end';

编辑

请改用此代码。这可以避免在未指定时间时出现的其他潜在语法错误。

// Store where clauses and values in arrays
$values = $where = array();

if (!empty($time)) { // @note better validation here
$where[] = ':time BETWEEN `start` AND `end`';
$values[':time'] = $time;
}

if (!empty($city)) { // @note better validation here
$where[] = '`city` = :city';
$values[':city'] = $city;
}

if (!empty($type)) { // @note better validation here
$where[] = '`type` = :type';
$values[':type'] = $type;
}

// Build query
$question = 'SELECT * FROM `events`';
if (!empty($where)) {
$question .= ' WHERE '.implode(' AND ', $where);
}

$query = $db->prepare($question);

$query->execute($values);

关于php - 使用 PDO 的 SELECT 查询失败,在 phpMyAdmin 中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11650189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com