0

I'm creating a simple search query for a tutorial which I'm working through, but it fails. I'm getting the following error:

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\xampp\htdocs\cms\blog.php on line 73

I'm new to php and don't understand what this means. Can anyone help a noob?

if(isset($_GET["search"])){

              $search = $_GET["search"];

              $sql = "SELECT * FROM posts WHERE
              datetime LIKE :Search
              OR title LIKE :Search
              OR category LIKE :Search
              OR author LIKE :Search
              OR post LIKE :search";

              $stmt = $connect->prepare($sql);
              $stmt->bindValue(':search','%'.$search.'%');
              $stmt->execute();
            }
Lab Lab
  • 781
  • 10
  • 34

1 Answers1

0

You have an error in your query in the binding parameters. I'd suggest you to edit your code as bellow:

if(isset(filter_input(INPUT_GET, "search", FILTER_SANITIZE_STRING))){

      //You should avoid accessing these global variables directly and use filter_input method to access them instead to make your application more secure
      $search = filter_input(INPUT_GET, "search", FILTER_SANITIZE_STRING);

      //Also possibly your server is case sensitive so it won't work if you use :Search for binding.
      $sql = "SELECT * FROM posts WHERE
      datetime LIKE :search
      OR title LIKE :search
      OR category LIKE :search
      OR author LIKE :search
      OR post LIKE :search";

      $stmt = $connect->prepare($sql);
      $stmt->bindValue(':search', "%{$search}%");
      $stmt->execute();
    }

I have added explanatory comments within the code sample above. Please read them for further explanation. I hope this helps.

Cheers!