Reputation: 11
Im trying to add search function. i want it to work like that: for exmple if i have 5 field, and user wrote only in 2, the search will be based only on 2 field. I mean it not neccesary to write information in all 5 field, i want search will happen only in filled fields.
And now it works only if i will write something in all fields (for now i have 2). And if i will write only in one field it doesnt show anything.
Code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<h1>Поиск</h1>
<form action="search_form.php" method="post">
<p>Направление</p>
<input type="text" name="course" />
<p>Форма обучения</p>
<input type="text" name="form" />
<input type="submit" value="Искать">
</form>
<?php
$db = mysql_connect("localhost", "root", "") or die (mysql_error ());
mysql_select_db("university", $db) or die(mysql_error());
$w = array('TRUE');
if (isset($_POST['course']))
{
$course = $_POST['course'];
$w[] = "course='$course'";
}
if (isset($_POST['form']))
{
$form = $_POST['form'];
$w[]= "form='$form'";
}
$where = implode($w, ' AND ');
$query = ('SELECT * FROM news WHERE '.$where);
$result = mysql_query($query,$db);
if($result !== false)
{
$news = mysql_fetch_array($result);
while($news = mysql_fetch_assoc($result)) {?>
<tr>
<td><?=$news['id']?></td>
<td><?=$news['program']?></td>
</tr><?
}
}
else
{
echo 'Sorry, we didn't find anything.';
}?>
</div>
</body>
</html>
Upvotes: 0
Views: 45
Reputation: 360562
You are vulnerable to SQL injection attacks. Learn about and fix that before you do ANYTHING else with this code.
Plus your logic is faulty: mysql_query()
returns false on errors. A query which has no results is NOT an error, and still returns a valid query handle. It'll simply have 0 rows on it.
$result = mysql_query($query);
if ($result === false) {
die(mysql_error());
} else if (mysql_num_rows($result) == 0) {
die("No results");
} else {
... display results
}
Upvotes: 1