我是PDO语句的新手,到目前为止,我已经设法使用它,使用预备语句和许多东西,直到今天。
我有两个查询,第一个检索一些数据,存储结果,然后第二个查询使用该数据来检索最终数据。我正在研究设计糟糕的数据库,这就是为什么我必须做奇怪的事情。
第一个查询获得体育联赛的开始年份和结束年份。然后,将年份传递给第二个查询以获取这些年份之间的数据(WHERE)。
问题是bindParam似乎不起作用,它不绑定参数,显示一个?,然后SQL抛出以下异常:
Connection failed: SQLSTATE[42000]: Syntax error or access violation:
1064 You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use
near ''0701' AND ?'0630' ORDER BY e.FECHA DESC' at line 5
SQL:
$sqlQueryAuxiliar = "SELECT ano_inicio, ano_fin
FROM TEMPORADAS
ORDER BY ano_inicio DESC
LIMIT 1;";
$sqlQuery = "SELECT e.id, e.JORNADA, DATE_FORMAT(e.FECHA, '%Y-%m-%d'),
e.HORA, c1.nombre_temporada, c2.nombre_temporada
FROM ENCUENTROS AS e
JOIN CLUBS AS c1 ON (e.COD_EQUIL = c1.siglas)
JOIN CLUBS AS c2 ON (e.COD_EQUIV = c2.siglas)
WHERE e.FECHA BETWEEN :anoInicio'0701' AND :anoFinal'0630'
ORDER BY e.FECHA DESC;";
这是PHP代码:
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmtAux = $this->_db->prepare($sqlQueryAuxiliar);
$stmtAux->execute();
$fetched = $stmtAux->fetchAll();
$stmtAux = null;
$stmt = $this->_db->prepare($sqlQuery);
$stmt->bindParam(':anoInicio', $fetched[0][0], PDO::PARAM_STR, 12);
$stmt->bindParam(':anoFinal', $fetched[0][1], PDO::PARAM_STR, 12);
$stmt->execute();
while ($row = $stmt->fetch()) {
$partidos[] = $row;
}
$stmt = null;
答案 0 :(得分:2)
您不能以这种方式在查询中连接字符串。将您的查询更改为
SELECT e.id, e.JORNADA, DATE_FORMAT(e.FECHA, '%Y-%m-%d'), e.HORA, c1.nombre_temporada, c2.nombre_temporada
FROM ENCUENTROS AS e
JOIN CLUBS AS c1 ON (e.COD_EQUIL = c1.siglas)
JOIN CLUBS AS c2 ON (e.COD_EQUIV = c2.siglas)
WHERE e.FECHA BETWEEN :anoInicio AND :anoFinal
ORDER BY e.FECHA DESC
和bindParam
到
$stmt->bindValue(':anoInicio', $fetched[0][0] . '0701', PDO::PARAM_STR);
$stmt->bindValue(':anoFinal', $fetched[0][1] . '0630', PDO::PARAM_STR);
答案 1 :(得分:1)
有理由说,你正在构建无效的sql:
WHERE e.FECHA BETWEEN :anoInicio'0701' AND :anoFinal'0630'
将基本上构建
WHERE e.FETCHA BETWEEN foobar'0701' AND barbaz'0630'
这是语法错误。
你可能想要
WHERE e.FETCH BETWEEN concat(:anoInicio, '0701') AND concat(:anoFinal, '0630')
代替。
答案 2 :(得分:0)
如果您使用的是绑定参数,则不应在查询中传递硬编码值。
"SELECT e.id, e.JORNADA, DATE_FORMAT(e.FECHA, '%Y-%m-%d'), e.HORA, c1.nombre_temporada, c2.nombre_temporada
FROM ENCUENTROS AS e
JOIN CLUBS AS c1 ON (e.COD_EQUIL = c1.siglas)
JOIN CLUBS AS c2 ON (e.COD_EQUIV = c2.siglas)
WHERE e.FECHA BETWEEN :anoInicio AND :anoFinal
ORDER BY e.FECHA DESC;";