3

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.

5
  • 1
    What does it display? What should it display? If $search_file is not being handled before putting it in the you've opened yourself to SQL injections (depending on how you are handling it could still be open). You are best off to use parameterized queries. Commented Dec 6, 2016 at 4:04
  • it's in the link sir. sorry its on 1drv. Commented Dec 6, 2016 at 4:06
  • I clicked the link took a while to load, I'm on DSL so maybe it's just me.. Commented Dec 6, 2016 at 4:07
  • i'm using mysqli, and it's just for education purposes. :) Commented Dec 6, 2016 at 4:10
  • mysqli does nothing to prevent SQL injections by default. Best to learn the right way first :), php.net/manual/en/mysqli.quickstart.prepared-statements.php Commented Dec 6, 2016 at 4:16

1 Answer 1

4

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' 
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, that's was fast. You're a great help!
sir i've forgot to put one data from the database. $sql = "SELECT * FROM tblAlumni WHERE (fname LIKE '%$search_file%' or mname LIKE '%$search_file%' or lname LIKE '%$search_file%', yeargrad LIKE '2017') AND alum_status LIKE 2".. is this correct?
@IKenat - No wrong you cannot have comma like that. Do you mean AND instead of comma
SELECT * FROM tblAlumni WHERE (fname LIKE '%$search_file%' or mname LIKE '%$search_file%' or lname LIKE '%$search_file%' AND yeargrad LIKE '$year') AND alum_status LIKE 2 this is what I've come up to.
Thank you sir. This was it. :) I'll accept your answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.