Dear friend, I don’t know if there are any more errors there, but from this bit of code you have there, I see only one irregularity capable of causing this problem, which is the number of parameters linked through the bindParam. In your consultation SQL were very specific providing two placeholders, with the names :title and :contents, but during the part where you linked the values of those respective placeholders, you just passed one.
Here are some corrections I applied to your script:
Example:
<?php
// Valores Extrnos
$key = isset($_GET["keyword"]) ? trim( (string) $_GET["keyword"]) : NULL;
// Conectar PDO
try{
$opc = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$pdo = new PDO("mysql:hostname=localhost;dbname=banco_de_dados;", "root", "", $opc);
//$sql = "SELECT * FROM noticias WHERE titulo LIKE :titulo OR conteudo LIKE :conteudo ORDER BY id ASC";
$sql = "SELECT * FROM noticias WHERE titulo LIKE :titulo OR conteudo LIKE :conteudo ORDER BY Nid";
$stmt = $pdo->prepare($sql);
$key = "%" . $key . "%";
$stmt->bindParam(":titulo", $key, PDO::PARAM_STR);
$stmt->bindParam(":conteudo", $key, PDO::PARAM_STR);
$stmt->execute();
// Capturar exceção, se haver uma
} catch(PDOException $e){
echo "Erro: " . $e->getMessage();
}
// Resultados
if(isset($stmt)){
while($linhas = $stmt->fetch(PDO::FETCH_OBJ)){
echo $linhas->titulo . "<br/>";
echo $linhas->conteudo. "<br/>";
}
}
?>
NOTE: Work with the PDO
, requires some care, and I also noticed that in this part of your script, you have the try
, but I didn’t see the part catch
where to capture the exception, in case there is any.
References:
PDO::bindParam - PHP.net
Exceptions - PHP.net
Catch - PHP.net
The problem is in the query and not in php. The idea is to search for
%:key%
? makes a sqlfiddle and puts the link in the question and queries that did not work.– rray