Creating an address book - how to display search results
Posted: Fri Jan 28, 2005 4:54 pm
Hi all, recently found this corner of the web, and so far it's been a great help. I'm new to PHP, and I'm creating a basic contacts database (MySQL, PHP) and so far I've managed on my own, but now I think that user error is hindering me. I've posted the PHP below, I hope that someone can point out my simple errors!
The problem: When I load the page, my search button and text field are displayed, but the text that should only be displayed when there are no matches is also displayed. When I enter a correct value into the search field, the page does not return the users. If it's any help, when I change the dynamic search variable to a static value (ie a known surname) the correct values are displayed in the table.
Thanks in advance for any tips and pointers, and any solutions that you have to offer
:t:
The problem: When I load the page, my search button and text field are displayed, but the text that should only be displayed when there are no matches is also displayed. When I enter a correct value into the search field, the page does not return the users. If it's any help, when I change the dynamic search variable to a static value (ie a known surname) the correct values are displayed in the table.
Thanks in advance for any tips and pointers, and any solutions that you have to offer
:t:
Code: Select all
<html>
<body>
<form method="POST" action="./search_test002.php">
Surname: <input type="text" name="query">
<input type="SUBMIT" value="Search">
</form>
<?php
// create MySQL connection
$connection=mysql_connect("server","user","password");
if (!$connection) {
echo "Could not connect to MySql server!";
exit;
}
// select database
$db=mysql_select_db("contacts",$connection);
if (!$db) {
echo "Could not select database";
exit;
}
//select record fields from database table and check for results
$sql="SELECT title,first_name,last_name, date_birth FROM users WHERE last_name = '%$query%' ";
$mysql_result=mysql_query($sql,$connection);
$num_rows=mysql_num_rows($mysql_result);
// We have no results
if ($num_rows == 0) {
echo "Sorry, we have no records";
} else {
// results returned so create a table to display them
echo "<TABLE BORDER="1">";
echo "<TR><TH>TITLE</TH><TH>FIRST NAME</TH><TH>LAST NAME</TH><TH>DATE OF BIRTH</TH></TR>";
//table population using a 'while' loop
while ($row=mysql_fetch_array($mysql_result))
{
$title=$rowї"title"];
$fname=$rowї"first_name"];
$lname=$rowї"last_name"];
$dob=$rowї"date_birth"];
//display the results under the correct headings
echo "<TR><TD>$title</TD><TD>$fname</TD><TD>$lname</TD><TD>$dob</TD></TR>";
}
}// End else while
//close the MySQL connection
mysql_close($connection);
?>
</TABLE>
</body>
</html>