PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I am trying to create a search bar which searches for users in the database, however as I have limited experience of MySQL in PHP and have never used foreach before (I am learning), I cannot see what the error is below:
<?php
ob_start();
include("database.php");
echo <<<END
<div>
<FORM NAME ="form1" METHOD ="POST" ACTION = "search.php">
<INPUT TYPE = "Text" VALUE ="" NAME = "search">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Search">
</div>
END;
if (isset($_POST['Submit1'])) {
$term = $_POST['search'];
echo $term;
echo "Hello";
$search = mysql_query("SELECT Username FROM 'notes_notes' WHERE Username LIKE '$term%'");
$search2 = mysql_fetch_array($search); # An error message complains about this line, saying 'Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource on line 20
$search4 = $search2->Username;
echo $term;
echo $search4;
foreach ($search2 as &$value) { # And here, with 'Warning: Invalid argument supplied for foreach() on line 24'
$search3 = $value->Username;
echo <<<END
<div>
$search3
</div>
END;
}
unset($value);
} else {
echo "Failed";
}
?>
It echoes $term properly, and in phpmyadmin it gives the correct result, albeit only if the full name has been entered ( Unless I add % to the end).
I had a look around and found that the mysql was failing because I had 'notes_notes' instead of notes_notes. This means that now I get no errors and it more or less works.
If the query failed when you used 'notes_notes' that's probably the reason why the mysql_fetch_array failed. When the query fails $query2 contains a different value then expected for mysql_fetch_array.
As for the Like, the % is a wildcard that mysql uses for matching, if you don't use the % at the end it will only find exact matches that match $term. If you place it at the end (term%) you get everything starting with $term, %$term gives back everything ending with $term and finally %$term% gives back everything containing $term.