Page 1 of 1

MySQL problem in PHP

Posted: Wed Aug 03, 2011 2:05 am
by ThatPerson
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:

Code: Select all

<?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";
}
?>

Re: MySQL problem in PHP

Posted: Wed Aug 03, 2011 4:16 am
by Dodon
You echo $term, does it give a value or is it empty?

If you execute the query in phpmyadmin, do you get a result or a mysql error?

Your foreach fails as a result of your mysql_fetch_array failing, since nothing is done to $query2.

Re: MySQL problem in PHP

Posted: Wed Aug 03, 2011 4:29 am
by ThatPerson
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.

Re: MySQL problem in PHP

Posted: Wed Aug 03, 2011 4:52 am
by Dodon
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.

Re: MySQL problem in PHP

Posted: Wed Aug 03, 2011 5:02 am
by ThatPerson
Ok, thanks for the help, it now works.