John23
John23

Reputation: 219

Pdo undefined index and invalid parameter number

I´m trying to develop a basic search system and I´m getting an issue with my pdo statement adding my $_SESSION to the sql statement.

Errors Im getting:

Notice: Undefined index: where in -> $readNews = $pdo->prepare("SELECT * from news $_SESSION[where] ORDER BY data");

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in -> $readNews->execute();

Somebody there see something that Im doing wrong?

if(isset($_POST['sendForm']))
    {
        $search = $_POST['search'];
        if(!empty($search) && $search != 'Title:')
        {
            $_SESSION['where'] = "WHERE title LIKE ?";
        }
        else
        {
            unset($_SESSION['where']);
        }

    }

PDO statement:

    $readNews = $pdo->prepare("SELECT * from news $_SESSION[where]  ORDER BY date");  
    $readNews->bindValue(1, "%$search%");
    $readNews->execute();

I already did this with normal mysql, like this and its working:

"select * from news {$_SESSION[where]} ORDER BY date DESC";

But now I´m trying to do with PDO..

Upvotes: 0

Views: 212

Answers (2)

Amit Garg
Amit Garg

Reputation: 3907

$_SESSION[where] should be {$_SESSION['where']}

Other wise interpreter try to find where as constant.

if(isset($_POST['sendForm']))
    {
        $search = $_POST['search'];
        if(!empty($search) && $search != 'Title:')
        {
            $_SESSION['where'] = "WHERE title LIKE ?";
        }
        else
        {
            $_SESSION['where']='';//changed here because you are trying to access it
        }

    }

and

$readNews = $pdo->prepare("SELECT * from news {$_SESSION['where']}  ORDER BY date");

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157864

Undefined index: where means there is no such item in your $_SESSION array

Upvotes: 1

Related Questions