Reputation: 219
I have a list of news and I have also a form to search for news.
So I created a session that stores an SQL command that I want to run if the search form is submitted, and so far it works well.
The problem is when the form is not submitted, my SQL command has the {$_SESSION[where]}
in the SQL statement and then I'm having an error undefined index 'where'.
So, the problem I'm having is that when I'm not passing any value to my $search
then the SQL command needs the value of $search
and then because I did not pass this value I've got the error saying that no such variable is defined.
I've been trying various alternatives for hours but I didn't find any good solutions, can you please give me a little help?
I have a form with the name sendForm
, then I have this code when the user submits the form:
<?php if(isset($_POST['sendForm']))
{
$search = $_POST['search'];
if(!empty($search) && $search != 'Search...')
{
$_SESSION['where'] = "AND titulo LIKE '%$search%'";
header('Location: index2.php?exe=posts/news');
}
//clean search
else
{
unset($_SESSION['where']);
header('Location: index2.php?exe=posts/news');
}
}
?>
Then I have my read statment for the articles but also for the search results:
$pag = (empty($_GET['pag']) ? '1' : $_GET['pag']);
$max = 15;
$begin = ($pag * $max) - $max;
$readNews = $pdo->prepare("SELECT * from news {$_SESSION[where]} ORDER BY data DESC LIMIT ?, ?");
$readNews->bindValue(1, $begin,PDO::PARAM_INT);
$readNews->bindValue(2, $max,PDO::PARAM_INT);
$readNews->execute();
Upvotes: 1
Views: 933
Reputation: 13128
If I understand this correctly; If the user/you does not supply a $search
query, you unset the session variable -> $_SESSION['where']
with this if block:
if(!empty($search) && $search != 'Search...')
{
$_SESSION['where'] = "AND titulo LIKE '%$search%'";
header('Location: index2.php?exe=posts/news');
}
//clean search
else
{
unset($_SESSION['where']);
header('Location: index2.php?exe=posts/news');
}
What you aren't doing though is checking if the session variable is set when you get to your PDO statements. Evident when looking at your snippet:
$pag = (empty($_GET['pag']) ? '1' : $_GET['pag']);
$max = 15;
$begin = ($pag * $max) - $max;
$readNews = $pdo->prepare("SELECT * from news {$_SESSION[where]} ORDER BY data DESC LIMIT ?, ?");
$readNews->bindValue(1, $begin,PDO::PARAM_INT);
$readNews->bindValue(2, $max,PDO::PARAM_INT);
$readNews->execute();
Assuming that you do check for session_start()
before this, you will need to add in a check to see that $_SESSION['where']
is set.
Something like this should suffice:
if(isset($_SESSION['where']) && !empty($_SESSION['where'])) {
// Do PDO query stuff
} else {
// No $search query supplied.....do something else.
}
Please correct me if I am wrong.
Upvotes: 1
Reputation: 897
Change
<?php if(isset($_POST['sendForm']))
to
<?php if(isset($_POST['sendForm']) && isset($_POST['search']))
Upvotes: 0