3
I’m migrating a system made in ASP to PHP. However, I’m having trouble making a query using PDO:
Search.php
class Busca extends Conexao {
private $termo;
public function setTermo($termo) { $this->termo = $termo; }
public function getTermo() { return $this->termo; }
public function listarResultados() {
try {
$pdo = parent::getDB();
$consulta = $pdo->prepare("SELECT D2.D2CDORG AS COD_ORGAO, D2.D2DSORG AS NME_ORGAO, D1.D1CDSRV AS COD_SERVICO, D1.D1DSSRV AS NME_SERVICO, D3.D3CDITM AS COD_ITEM, D3.D3DSITM AS NME_ITEM, D3.D3VALOR * (SELECT D7VLREAL FROM D7VRTE WHERE D7AAMMREF = 11) AS VALOR FROM D5ITMORGSRV D5, D3ITENS D3, D2ORGAOS D2, D1SERVICOS D1 WHERE (D1.D1CDSRV <> 5) AND (D5.D1CDSRV = D1.D1CDSRV) AND (D5.D2CDORG = D2.D2CDORG) AND (D5.D3CDITM = D3.D3CDITM) AND ((D3.D3DSITM LIKE :termo) OR (D1.D1DSSRV LIKE :termo)) ORDER BY NME_ORGAO, NME_SERVICO, NME_ITEM");
$consulta->bindValue(':termo', $this->getTermo());
$consulta->execute();
return $consulta->fetchAll(PDO::FETCH_OBJ);
} catch (PDOException $e) {
echo "<p class='alert alert-danger'><b>Ocorreu um erro: </b>" . $e->getMessage() ."</p>";
}
}
}
Results page:
$busca = new Busca;
$busca->setTermo('identidade');
$resultado = new ArrayIterator($busca->listarResultados());
The return is:
SQLSTATE[07002]: COUNT field incorrect: 0 [Microsoft][ODBC SQL Server Driver]Campo COUNT incorreto ou erro de sintaxe (SQLExecute[0] at ext\pdo_odbc\odbc_stmt.c:133)
Researching, I saw that it is in the bindValue
, but I’ve tried everything and nothing works.
I tried to use two bindValue
(:termo1
and :termo2
). Does not give the above error, but returns ArrayIterator Object ( )
in the print_r
.
If instead of :termo
pass by '%identidade%
', for example, the data is shown correctly.
That’s how it works: (LIKE '%".$this->getTermo()."%'
)
$consulta = $pdo->prepare("SELECT D2.D2CDORG AS COD_ORGAO, D2.D2DSORG AS NME_ORGAO, D1.D1CDSRV AS COD_SERVICO, D1.D1DSSRV AS NME_SERVICO, D3.D3CDITM AS COD_ITEM, D3.D3DSITM AS NME_ITEM, D3.D3VALOR * (SELECT D7VLREAL FROM D7VRTE WHERE D7AAMMREF = 11) AS VALOR FROM D5ITMORGSRV D5, D3ITENS D3, D2ORGAOS D2, D1SERVICOS D1 WHERE (D1.D1CDSRV <> 5) AND (D5.D1CDSRV = D1.D1CDSRV) AND (D5.D2CDORG = D2.D2CDORG) AND (D5.D3CDITM = D3.D3CDITM) AND ((D3.D3DSITM LIKE '%".$this->getTermo()."%') OR (D1.D1DSSRV LIKE '%".$this->getTermo()."%')) ORDER BY NME_ORGAO, NME_SERVICO, NME_ITEM");
How to solve this?
When it passed
:termo1
and:termo2
put the%
at the consultation or onbindvalue()
?– rray
In the query. But it still doesn’t work. I tried to use
?
instead of:termo
. Changes nothing..– buback