CherylAnnCE CherylAnnCE - 1 year ago 48
MySQL Question

Display search criteria in search box while results are being displayed with PHP

I have a search form and am displaying the results on the same page as the search form. So, before a search takes place, all the possible results are visible. Once a keyword is entered into the form, the results are only those that contain the keyword. I would like the form to display the keyword that was entered into the form when the results are displayed. I have tried multiple things and my latest attempt is to enter into various parts of the form, but with no luck. I have searched multiple tutorial sites and am not finding this particular request to be addressed. Can any of you help me to get the search criteria to remain in the search box when the results are displayed? Here is the code I am using:

<html>
<body>
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
<?php
function getRecords($query) {
$con = mysql_connect("localhost", "movie", "moviepw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("movies", $con);

$result = mysql_query($query);
return $result;
}

function buildQuery() {

$keyword = $_GET['keyword'];
$sql = "SELECT * from table1 WHERE (movie_title LIKE '%$keyword%'
OR movie_description LIKE '%$keyword%')";
return $sql;
} ?>

<form action="movie_form.php" method=get>
<fieldset>
<legend>Movies</legend>
<label for="keyword">Search</label>
<input id="keyword" name="keyword" />
<input type=submit name=submit value=Search />
<? echo $keyword ?>
</fieldset>
</form>

<?
$query = buildQuery();
$records = getRecords($query);

while($row = mysql_fetch_array($records)){ ?>
<table>
<tbody>
<table border='1'>
<tr>
<td><?= $row['movie_title']; ?></td>
<td><?= $row['movie_rating']; ?></td>
<td><img src="<?= $row['movie_image'];?>"></td>
<td><?= $row['movie_description']; ?></td>
<td><a href="movie_form.php">Return to Search</a></td>
</tr>
<? } ?>
</tbody>
</table>
</body>
</html>

Answer Source

Add the "value" attribute to your "keyword" form input. Something like this:

<input id="keyword" name="keyword" value="<?php echo "$keyword"; ?>"/>

Also, move the setting of $keyword out of the buildQuery() method so that it will be available when your form is output. You could put it right after error_reporting is set:

<?php error_reporting (E_ALL ^ E_NOTICE); 
      $keyword = rtrim($_GET['keyword']);
?>

Finally, this code is vulnerable to sql injection. Check this out: How can I prevent SQL injection in PHP?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download