Johnson
Johnson

Reputation: 818

PHP: Searching in database

I have made an normal form that you can enter a user´s fullname in and choose sex.

Now to the PHP for the searching in the database.

$full_name = mysql_real_escape_string($_POST["search"]);
$sex = mysql_real_escape_string($_POST["sex"]);
list($firstname, $lastname) = array_map('ucfirst', explode(' ', $full_name));
        $query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE firstname LIKE '$firstname' OR lastname LIKE '$lastname' AND sex = '$sex'"; 
    $result1 = mysql_query($query) or die(mysql_error());
    $count = mysql_num_rows($result1);
echo $count;

If i enter Jenni Jackson (that exists) and choose "male", i still get 1 in $count, but Jenni Jackson is a female, and has female in the sex column.. I tried do echo $sex to see the value of $sex if it really is what you chose in the form, and it is correct.

Upvotes: 1

Views: 1086

Answers (4)

aeon
aeon

Reputation: 89

Try adding some brackets

$query = "
    SELECT 
         firstname, 
         lastname, 
         id, 
         user_name, 
         sex, 
         last_access, 
         bostadsort 
     FROM users 
     WHERE 
        (
         firstname LIKE '$firstname' 
         OR lastname LIKE '$lastname'
        ) 
        AND sex = '$sex'"; 

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

You're combining AND and OR conditions in the same WHERE clause

Do you mean

(firstname LIKE '$firstname' OR lastname LIKE '$lastname') AND sex = '$sex'

or

firstname LIKE '$firstname' OR (lastname LIKE '$lastname' AND sex = '$sex')

Upvotes: 0

Gus
Gus

Reputation: 7349

You need brackets in your WHERE clause so that the database knows which takes precedence (AND or OR):

WHERE (firstname LIKE '$firstname' OR lastname LIKE '$lastname') AND sex = '$sex'

Upvotes: 0

codaddict
codaddict

Reputation: 455000

You need to use parenthesis in your query as:

WHERE (firstname LIKE '$firstname' OR lastname LIKE '$lastname') AND sex='$sex'";

without the parenthesis your query is equivalent to:

WHERE firstname LIKE '$firstname' OR (lastname LIKE '$lastname' AND sex='$sex')";

and since firstname condition matches, the row is returned.

This happens because AND is having precedence over OR

Upvotes: 3

Related Questions