I am practicing with php mysql search results. The only problem I am getting is that the search isn’t consistent in returning results.
Please visit:
weezy.co.uk/newresults.php
type in ‘trainee’ in the first search box at the top.
Sometimes the results show sometimes they don’t. I don’t get it?
my HTML search box code is:
<form action="newresults.php" method="post" name="form">
<input type="text" id="search" name="search"
size="30" value="" style="background- color:white; border:
solid 1px #ffffff; height: 30px; font-size:19px; font-family:
HelveticaNeue-Light; font-weight: 1;
vertical-align:9px;color:#151515"
onfocus="if(this.value == ''){this.value =
'';this.style.color='#363D42'}" />
</div>
</div>
<div class="search">
<div class="search1">
<input type="text"
id="searchterm" name="searchterm" size="25" value="" style="background-
color:white; border:
solid 1px #ffffff; height: 30px; font-size:19px; font-family:
HelveticaNeue-Light; font- weight: 1;
vertical-align:9px;color:#151515"
onfocus="if(this.value == ''){this.value =
'';this.style.color='#363D42'}" />
</form>
php code:
<?php
$conn = mysql_connect("", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("weezycouk_641290_db1")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '$search%' AND lastname LIKE '$searchterm%'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br>';
echo '<br>';
echo '<div class="data1">';
echo $row["name"];
echo '</div>';
echo '<br>';
echo '<div class="data2">';
echo $row["lastname"];
echo '</div>';
echo '<br>';
echo '<div class="data3">';
echo $row["email"];
echo '</div>';
}
mysql_free_result($result);
?>
Thanks guys!
James
When your page loads with results, you also load a “Tags” sidebar with the question “Want the recruiters to find you?” The input boxes in that sidebar are filled in with “Enter name” and “Enter chosen industry.” The “name” attribute on both those inputs is “search,” so you are posting multiple fields named “search.”
Just change the names on the inputs in your sidebar to fix this bug. You should definitely sanitize the inputs (as others have noted), too.