如何检查数据库列中存在的字符串? [英] how to Check string present in database column?
问题描述
我有一个文档表,其中的字段id
,sender_id
,receiver_id
和receiver_id
包含类似于 U12,U13,U14 的字符串值,现在我已登录用户,我想查找其中receiver_id
包含我的user_id
的所有记录,这意味着我的user_id
是U13
.现在如何编写查询以获取记录.
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.
我的查询是:
$selDoc="SELECT * FROM documents WHERE sender_id='U".$_SESSION['userId']."' OR "U".$_SESSION['userId']." IN (receiver_id) ORDER BY id DESC";
但是我在"where子句"中收到错误未知列" U13"
but I got the error Unknown column 'U13' in 'where clause'
推荐答案
您的字符串连接混乱了,它应该是:(进一步简化)
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
作为附带说明,如果值( s)是 SQL Injection
,则该查询容易受到攻击)的变量来自外部.请查看下面的文章,以了解如何防止它.通过使用PreparedStatements
,您可以避免在值周围使用单引号.
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.
这篇关于如何检查数据库列中存在的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!