MySQL查询——检查数据行是否包含user_id

时间:2022-12-19 14:53:20

I have a sessions table and what I am trying to do is run a query to check if a certain account is logged in.

我有一个会话表,我要做的是运行一个查询来检查某个帐户是否已登录。

MySQL查询——检查数据行是否包含user_id

My query looks like this:

我的查询是这样的:

SELECT id FROM sessions WHERE data LIKE '%4%' 

But with a query like that, if the user_id of "14" is logged in, that query will return True. How do I check to see if a certain number exists and matches exactly?

但是对于这样的查询,如果登录了“14”的user_id,该查询将返回True。如何检查某个数字是否存在并与之精确匹配?

2 个解决方案

#1


4  

Include the delimiters in your search:

在搜索中包括分隔符:

WHERE data LIKE '%:4;%'

#2


1  

why don't you add another field for user_id to the session table?

为什么不向会话表添加user_id的另一个字段呢?

EXAMPLE: I have a site where a user can only be logged in from one location at a time. If they try and log in from another location (IE start a new session) then i kill all of their previous logins.

示例:我有一个站点,用户每次只能从一个位置登录。如果他们尝试从另一个地方登录(即开始一个新的会话),那么我就会终止他们之前的所有登录。

So as part of my login script:

作为登录脚本的一部分:

// log this user out of any other active sessions
$sql = sprintf("DELETE 
    FROM sessions 
    WHERE id_user=%s", 
    mysql_real_escape_string($_SESSION['id_user'])
);

// Associate this session with this user
$sql = sprintf("UPDATE sessions 
    SET id_user=%s 
    WHERE id=%s", 
    mysql_real_escape_string($_SESSION['id_user']), 
    session_id()
);

and so i can have id_user as an additional field in my session FKed to my user table... its a little more normalized and lets you do quick "Who is currently using this site" queries without too much parsing and fuss.

因此,我可以让id_user作为会话中的一个附加字段,在我的用户表中添加…它更规格化一些,让您可以快速地执行“谁正在使用这个站点”查询,而不会有太多的解析和麻烦。

#1


4  

Include the delimiters in your search:

在搜索中包括分隔符:

WHERE data LIKE '%:4;%'

#2


1  

why don't you add another field for user_id to the session table?

为什么不向会话表添加user_id的另一个字段呢?

EXAMPLE: I have a site where a user can only be logged in from one location at a time. If they try and log in from another location (IE start a new session) then i kill all of their previous logins.

示例:我有一个站点,用户每次只能从一个位置登录。如果他们尝试从另一个地方登录(即开始一个新的会话),那么我就会终止他们之前的所有登录。

So as part of my login script:

作为登录脚本的一部分:

// log this user out of any other active sessions
$sql = sprintf("DELETE 
    FROM sessions 
    WHERE id_user=%s", 
    mysql_real_escape_string($_SESSION['id_user'])
);

// Associate this session with this user
$sql = sprintf("UPDATE sessions 
    SET id_user=%s 
    WHERE id=%s", 
    mysql_real_escape_string($_SESSION['id_user']), 
    session_id()
);

and so i can have id_user as an additional field in my session FKed to my user table... its a little more normalized and lets you do quick "Who is currently using this site" queries without too much parsing and fuss.

因此,我可以让id_user作为会话中的一个附加字段,在我的用户表中添加…它更规格化一些,让您可以快速地执行“谁正在使用这个站点”查询,而不会有太多的解析和麻烦。