3

I have a simple search script to search a database which should return all the rows of data that match the search query that belong to that user, however my query (below) is returning rows from every user. Any idea how to fix this?

SELECT * FROM tablename 
WHERE title LIKE '%" . $q . "%' 
OR text LIKE '%" . $q . "%' 
AND user='$user'

Side Note: This is executed in PHP so the $q is the variable that holds the query.

3
  • $user is a PHP variable, right? Commented Nov 18, 2012 at 3:52
  • @BryanH yes it contains the username from a session variable (defined earlier) Commented Nov 18, 2012 at 3:52
  • 2
    i am sure you aware of sql injunction Commented Nov 18, 2012 at 3:54

3 Answers 3

2

Have you tried this?

"SELECT * FROM tablename WHERE (title LIKE '%".$q."%' OR text LIKE '%".$q."%') AND user='$user'"
Sign up to request clarification or add additional context in comments.

5 Comments

This works great for the null input value however if a space is entered either by itself "[SPACE]" or in a statement "word[SPACE]"... Nothing is returned.
@4cpukid, can you provide an example where nothing is returned by echoing the query string?
@Mike "[SPACE]" and anything that has a [SPACE] in it. So if I search "birds[SPACE]" even if there is not a second word it won't even return the rows with "birds".
@4cpukid also try ' or '1'='1
@Stephen, that's not the query string. I mean the whole thing including SELECT * FROM etc.
0

Clear the $user variable of any white space before trying the SQL query

1 Comment

Why would white space affect it?
0

Try this:

<?php 
...
echo "SELECT * FROM tablename 
WHERE title LIKE '%" . $q . "%' 
OR text LIKE '%" . $q . "%' 
AND user='$user'";

And see what the output looks like.

Just as an aside, you can probably get away with

WHERE title LIKE '%$q%'

(i.e., not having to concatenate the query string). This will keep your code a bit cleaner and reduce errors (from missing a period/quote).

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.