-3

I'm trying to do a different sql statement in case that the user submit the search form. I'm trying with this code below, but I'm getting an error and I'm not understanding why, because the code seems gode for me.

Do you see here something that can be the cause of these errors?

Errors Im getting:

Call to a member function bindParam() on a non-object in $readNews->bindParam

Notice: Undefined variable: readNews in $readNews->bindParam(':begin', begin, PDO::PARAM_INT);

Fatal error: Call to a member function bindParam() on a non-object in F:\Xampp\htdocs\projeto\admin\posts\noticias.php on line 53

My code:

$pag = (empty($_GET['pag']) ? '1' : $_GET['pag']);
$maximo = 5; 
$begin = ($pag * $max) - $max;   

if (isset($_POST['search'])) 
{
$search = $_POST['search'];
if(!empty($search) && $search != 'Title:')
{
$readNews = $pdo->prepare("SELECT * FROM news WHERE title LIKE CONCAT('%', :search, '%') ORDER BY data DESC LIMIT :begin, :max");
$readNews->bindParam(':search', $search);
}
}       
else
{
$readNews = $pdo->prepare('SELECT * FROM news ORDER BY data DESC LIMIT :begin, :max');
}

$readNews->bindParam(':begin', begin, PDO::PARAM_INT);
$readNews->bindParam(':max', $max, PDO::PARAM_INT);
$readNews->execute();
$resultReadNews = $readNews->rowCount();
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
John23
  • 219
  • 2
  • 9
  • 31

1 Answers1

2

You are not handling one case: When isset($_POST['search']) is true and !empty($search) && $search != 'Title:' is false. In this case $readNews parameter is not initialized and statement is not prepared, explains both errors.

mesutozer
  • 2,839
  • 1
  • 12
  • 13