how to Check string present in database column? [c

2019-07-07 05:20发布

I have document table with fields id, sender_id, receiver_id and receiver_id contains string value like U12,U13,U14 now I currently logged in user and I want to find all records in which receiver_id contains my user_id means my user_id is U13. now how to write the query to fetch records.

my query is:

$selDoc="SELECT * FROM documents WHERE sender_id='U".$_SESSION['userId']."' OR  "U".$_SESSION['userId']." IN (receiver_id) ORDER BY id DESC";

but I got the error Unknown column 'U13' in 'where clause'

2条回答
放荡不羁爱自由
2楼-- · 2019-07-07 05:55

You're missing a quote there. Furthermore you should consider using bind variables in your query (assigning the values to look for to variables and then using placeholders in your query) to avoid problems of SQL injection (If you dont know what that is, look it up, it is vitally important to know!)

查看更多
Evening l夕情丶
3楼-- · 2019-07-07 06:05

You string concatenation is messed up, it should be: (further simplified)

$selDoc="SELECT * FROM documents WHERE 'U".$_SESSION['userId']."' IN (senderID,receiver_id) ORDER BY id DESC";

when the statement above is parsed, it will then look like this:

SELECT * 
FROM   documents 
WHERE  'UXX' IN (senderID,receiver_id)  // where XX is the userID
ORDER  BY id DESC

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

查看更多
登录 后发表回答