Coveraver Coveraver - 6 months ago 9
PHP Question

How to catch empty query in php

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>

Answer

After you read this post about SQL-injection, change

if (isset($_POST['search'])) {

to

if (!empty($_POST['search'])) {
Comments