April 25, 2012
Seach.php is not working and not showing any results
Question by Erik
I’m trying to figue out how to make my search.php script work with mySQL. I can’t get the information to show up. Not sure where the problem is.
PAGE 1:
<form action="search_result.php" method="GET">
<input type="text" name="reg" />
<input type="submit" value="Search" />
</form>
PAGE 2:
<?php
$host="localhost";
$username="XXXXXXXXXXX";
$password="XXXXXXXXXXX";
$db_name="XXXXXXXXXXXX";
$tbl_name="reg_add";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$record = $_POST['record']; // if coming from e.g. a form
$result=mysql_query(" SELECT * FROM reg_add WHERE reg='" . mysql_real_escape_string($record) . "'");
$row = mysql_fetch_assoc($result);
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$reg = $row['reg'];
?>
<input name="reg" value="<? echo "$record" ?>">
<input name="first_name" value="<? echo "$first_name" ?>">
<input name="last_name" value="<? echo "$last_name" ?>">
Answer by Adriaan
You form is method GET and in your PHP you use this:
$record = $_POST['record']; // if coming from e.g. a form
How are you gonna get the POST[‘record’] if your form has the method GET?
I guess you should or change your form to:
method="POST"
or change your $record in php to:
$record = $_GET['record'];
Try this version:
You form:
<form action="search_result.php" method="POST">
<input type="text" name="reg" id="reg" />
<input type="submit" name="Submit" id="Submit" value="Search" />
</form>
search_result.php :
<?php
$host ="localhost";
$username ="XXXXXXXXXXX";
$password ="XXXXXXXXXXX";
$db_name ="XXXXXXXXXXXX";
$tbl_name ="reg_add";
/* Connect to MySQL database */
mysql_connect("$host", "$username", "$password") or die("Error connecting to database");
mysql_select_db("$db_name")or die("Error selecting database");
$error = '';
if (isset($_POST['Submit'])) {
if (!empty($_POST['reg'])) {
$record = $_POST['reg']; // if coming from e.g. a form
$query = mysql_query("SELECT * FROM reg_add WHERE reg='" . mysql_real_escape_string($record) . "'");
$result = mysql_num_rows($query);
if ($result != 0) {
$row = mysql_fetch_array($query);
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$reg = $row['reg'];
} else {
$error = 'No result have been found!';
}
} else {
$error = 'You have not entered the search field, <a href="javascript:history.back(1)">Go back</a>.';
}
}
if (!empty($error)) { echo $error; }
?>
<input name="reg" value="<? echo $record; ?>">
<input name="first_name" value="<? echo $first_name; ?>">
<input name="last_name" value="<? echo $last_name; ?>">