Search without returning PDO data

Asked

Viewed 462 times

1

My variable is being passed but the filter process is always not returning anything.

try 
{
   $keyword = trim($_GET["keyword"]);
   if (!empty($keyword)) 
   {

       $sql = "SELECT * FROM noticias WHERE 
         titulo LIKE :keyword OR conteudo LIKE :keyword ORDER BY Nid";

       $stmt = $DB->prepare($sql);

       $likekeyword = "%".$keyword."%";
       $stmt->bindParam(':keyword', $likekeyword, PDO::PARAM_STR);

   } 
   else 
   {
       $sql = "SELECT * FROM noticias WHERE 1 ORDER BY Nid ";
       $stmt = $DB->prepare($sql);
   }

   $stmt->execute();

tried (titulo LIKE :termo) OR ...

Updated the strange and that the result of if empty blank is working which leads me to believe that and in the same consultation part

  • 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.

2 answers

2


I believe your problem will be solved in this way:

try {
     $termo = trim($_GET["termo"]);
      if (!empty($termo)) {
$sql = "SELECT * FROM noticias WHERE titulo LIKE :termo OR conteudo LIKE :termo ORDER BY Nid";
$stmt = $DB->prepare($sql);

$likeTermo = "%".$termo."%";
$stmt->bindParam(':termo', $likeTermo, PDO::PARAM_STR);
...

Consider these differences:

PDOStatement::bindValue() -> The variable is linked to the reference and will only be evaluated when the PDOStatement::execute() is called. And in this case, only values are accepted as argument.

If you use $stmt->bindValue(":termo", $termo);.
The value must exist, otherwise an error will occur.

PDOStatement::bindParam() -> Already in this case, the expected argument is a reference (variable or constant) and cannot be a primitive type like a string or loose number, function return or method.

Invalid examples:

$stmt->bindParam(':termo', 10); // Inválido
$stmt->bindParam(':termo', getValue()); // Inválido
  • unfortunately does not continue returning anything, had tried something like this before, I tested again to be sure however the result is the same

  • as the difference of param and value understood , thanks for the tip but still without the results, updated the code

  • maybe the problem is not in this stretch. And yes in the output, what happens when you give a var_dump($stmt->execute()) ?

  • And what happens when you run this query with the direct term in Workbench or phpmyadmin?

  • bool(true) returns true , displays the message I programmed ( no search was found) and I only have in the titles 3 results of the words I searched

  • when you perform: SELECT * FROM noticias WHERE titulo LIKE '%a%' OR conteudo LIKE '%a%' ORDER BY Nid in Workbench, which returns?

  • I have executed the following: SELECT * FROM noticias WHERE title LIKE audio OR content LIKE audio ORDER BY Nid LIMIT 0 , 30 and the result was incredible http://prntscr.com/8ow940 Can this happen?...

  • anything see, if the parameters are being processed: $stmt->debugDumpParams(); at the end of ...->execute()

  • SQL: [88] SELECT * FROM noticias WHERE title LIKE :keyword OR content LIKE :keyword ORDER BY Nid Params: 1 Key: Name: [8] :keyword paramno=-1 name=[8] ":keyword" is_param=1 param_type=2 result . more like starting in I don’t even know what you’re talking about, these param are the variables? or fields?

  • Here’s what it’s about, check your query: http://php.net/manual/en/pdostatement.debugdumpparams.php

  • Boy I discovered something if I search for "a" it returns me the result whose first letter of the contents is "a". I seem to be just checking the first word

  • 1

    When you use like, the % symbol represents any occurrence, if you are left (%abc) any occurrence starting with "abc" on the right using abc%, means any occurrence ending with "abc". can also use _ as a single-character wildcard. Use wildcards to make the query. by the way, this query you did treating ...LIKE audio ... audio word, no quotes is not a search term, it enters as a value "null".

Show 7 more comments

1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.