0

我是 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;
4

3 回答 3

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

bindParams

$stmt->bindValue(':anoInicio', $fetched[0][0] . '0701', PDO::PARAM_STR);
$stmt->bindValue(':anoFinal', $fetched[0][1] . '0630', PDO::PARAM_STR);
于 2013-03-11T16:43:43.337 回答
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')

反而。

于 2013-03-11T16:43:37.940 回答
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;";
于 2013-03-11T16:43:36.090 回答