Newbie's problems with MySQL and php
- by Mirage81
I'm a real newbie with php and MySQL. Now I'm working on the following code which should search the database for eg. all the Lennons living in Liverpool.
1) How should I modify "get.php" to get the text "no results" to appear if there are no search results.
2) How should I modify "index.php" to get the option values (city and lastname) straight from the database instead of having to type them one by one?
3) Am I using mysql_real_escape_string the right way?
4) Any other mistakes in the code?
index.php:
<form action="get.php" method="post">
<p>
<select name="city">
<option value="Birmingham">Birmingham</option>
<option value="Liverpool">Liverpool</option>
<option value="London">London</option>
</select>
</p>
<p>
<select name="lastname">
<option value="Lennon">Lennon</option>
<option value="McCartney">McCartney</option>
<option value="Osbourne">Osbourne</option>
</select>
</p>
<p>
<input value="Search" type="submit">
</p>
</form>
get.php:
<?php
$city = $_POST['city'];
$lastname = $_POST['lastname'];
$conn = mysql_connect('localhost', 'user', 'password');
mysql_select_db("database", $conn) or die("connection failed");
$query = "SELECT * FROM users WHERE city = '$city' AND lastname = '$lastname'";
$result = mysql_query($query, $conn);
$city = mysql_real_escape_string($_POST['city']);
$lastname = mysql_real_escape_string($_POST['lastname']);
echo $rowcount;
while ($row = mysql_fetch_row($result))
{
if ($rowcount == '0')
echo 'no results';
else
{
echo '<b>City: </b>'.htmlspecialchars($row[0]).'<br />';
echo '<b>Last name: </b>'.htmlspecialchars($row[1]).'<br />';
echo '<b>Information: </b>'.htmlspecialchars($row[2]);
}
}
mysql_close($conn);