Reputation: 159
I have several articles in my db and search on my site. if the user does not enter anything and click search, then displays all articles. How to catch empty request?
Code:
<?php
mysql_connect("localhost", "user", "password") or die("Error");
mysql_select_db("selv_hram") or die("Error");
mysql_query('SET names "utf8"');
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = htmlspecialchars($searchq);
$query = mysql_query("SELECT * FROM articles WHERE title LIKE '%$searchq%' OR text_article LIKE '%$searchq%'");
$count = mysql_num_rows($query);
$output = '';
if ($count == 0) {
$output = 'Nothing find';
}else {
while ($row = mysql_fetch_array($query)) {
$title = $row['title'];
$text = $row['text_article'];
$id = $row['id'];
$output .= '<div>'.$title.' '.$text.'</div>';
}
}
}
?>
<div class="content-article">
<form name="search" action="index.php" method="post" class="search-form">
<input type="text" name="search" placeholder="search" />
<input type="submit" value=">>">
<?php print("$output"); ?>
</div>
Upvotes: 0
Views: 555
Reputation: 290
After you read this post about SQL-injection, change
if (isset($_POST['search'])) {
to
if (!empty($_POST['search'])) {
Upvotes: 2
Reputation: 3879
Check the user input first, if it is empty change the query. like below
$searchq = htmlspecialchars($searchq);
if(trim($searchq) == ''){
$query = mysql_query("SELECT * FROM articles");
}else{
$query = mysql_query("SELECT * FROM articles WHERE title LIKE '%$searchq%' OR text_article LIKE '%$searchq%'");
}
Dont use depreciated mysql_ functions. Go for mysqli
Upvotes: 0
Reputation: 1883
This is simple validation.
if(empty($_POST['search'])) {
echo "Empty search query";
} else {
//search query
}
Upvotes: 0