我有一些PHP腳本與mysql_query一起工作,但現在我正在嘗試將其更改爲PDO(以減少他們所說的脆弱性和安全性),但我在使用條件選擇查詢時遇到了一些問題。 我有以下代碼:有條件的選擇查詢與PDO
$querydatahora = $conn->prepare('SELECT
Linhas.NomeLinha, Maquinas.Nome as maquina, Tecnicos.Nome, Avarias.DataHoraInicioAvaria,
Avarias.DataHoraFimAvaria, Avarias.Descricao, Avarias.Solucao, Avarias.TipoSolucao
FROM Avarias, Tecnicos, Linhas, Maquinas, avariatecnico
where Linhas.IDLinha = Avarias.IDLinha and avariatecnico.IDAvaria = avarias.IDAvaria and Avariatecnico.IDTecnico = Tecnicos.IDTecnico and
Maquinas.IDMaquina = Avarias.IDMaquina and DataHoraInicioAvaria >= :datetimepicker AND DataHoraFimAvaria <= :datetimepicker1 ');
if($_SESSION['IDLinha']) {
$querydatahora .= $conn->prepare(" AND Avarias.IDLinha = :IDLinha AND Avarias.IDMaquina = :IDMaquina order by DataHoraInicioAvaria DESC LIMIT $startrow, 9");
} else{
$querydatahora .= $conn->prepare(" order by DataHoraInicioAvaria DESC LIMIT $startrow, 9");
}
$querydatahora->execute(array(
':datetimepicker' => $_SESSION['datetimepicker'],
':datetimepicker1' => $_SESSION['datetimepicker1'],
':IDLinha' => $_SESSION['IDLinha'],
':IDMaquina' => $_SESSION['IDMaquina'])
);
if($_SESSION['IDLinha']) {
$querycount .= $conn->prepare(' AND Avarias.IDLinha = :IDLinha AND Avarias.IDMaquina = :IDMaquina');
}
$querycount->execute(array(
':datetimepicker' => $_SESSION['datetimepicker'],
':datetimepicker1' => $_SESSION['datetimepicker1'],
':IDLinha' => $_SESSION['IDLinha'],
':IDMaquina' => $_SESSION['IDMaquina'])
);
我得到的錯誤是:
Catchable fatal error: Object of class PDOStatement could not be converted to string in C:\xxxxxxxxxxxxxxxxxxxxxxxxxx.php on line 52
我不是專家對這個的話,也許我正在做一些錯誤。所有幫助表示讚賞
'準備()'返回'PDOStatement'對象,它就是你的例外是從哪裏來的,它不是一個字符串。您應該只傳遞'prepare()'完整的查詢,即將SQL查詢(使用佔位符)生成一個字符串,然後運行'prepare()'傳遞完整的查詢字符串。 –
您需要在調用$ conn-> prepare之前組裝您的查詢... $ querydatahora不像您想象的那樣是一個像「SELECT ...」這樣的字符串,而是一個對象htat接收到基於該字符串的預準備語句。 –
如果您使用加入,我認爲會更容易... – rray