Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL syntax does not give errors but displays wrong data

Tags:

sql

php

I'm just new here.

I would like to ask if my following SQL is correct and where did I do wrong?

This is my SQL in my php file

$sql = "SELECT * FROM tblAlumni WHERE fname LIKE '%$search_file%' or mname LIKE '%$search_file%' or lname LIKE '%$search_file%' AND alum_status LIKE 2"

It got no errors whatsoever but it doesn't display the correct data.

This is my table

Click here

and the result if i've search it or query it is this

Click here Thank you for future answers.


1 Answers

Your query will be executed like this

SELECT *
FROM   tblAlumni
WHERE  fname LIKE '%$search_file%'
        OR mname LIKE '%$search_file%'
        OR ( lname LIKE '%$search_file%'
             AND alum_status LIKE 2 ) 

because AND has higher precedence than OR. Parenthesis are very important for execution of Where clause

SELECT *
FROM   tblAlumni
WHERE  ( fname LIKE '%$search_file%'
          OR mname LIKE '%$search_file%'
          OR lname LIKE '%$search_file%' )
       AND alum_status = 2 

Use = instead of LIKE when you are looking for exact match it makes more sense to me

Update :

SELECT *
FROM   tblAlumni
WHERE  ( fname LIKE '%$search_file%'
          OR mname LIKE '%$search_file%'
          OR lname LIKE '%$search_file%' )
       AND alum_status LIKE 2
       AND yeargrad LIKE '$year' 
like image 134
Pரதீப் Avatar answered Nov 26 '25 05:11

Pரதீப்



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!