简体   繁体   中英

Laravel - How to use session username in query

I am trying to display a table based on session username but I am getting the following error. When it is id it is working but when it is username it is not

SELECT tb_list.* FROM tb_list  
WHERE myusername = ".Session::get('username')."

QueryException in Connection.php line 662: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY id asc LIMIT 0 , 10' at line 2 (SQL: SELECT tb_list. FROM tb_list WHERE username = ORDER BY id asc LIMIT 0 , 10 )*

Thanks in advance

Lets say the session owner's username is john

Table with NO session
WHERE tb_list.task_id IS NOT NULL
+---------+----------+-------------+-----------------+
| task_id | username |  some_data  |    some_time    |
+---------+----------+-------------+-----------------+
|    1    |   john   |  some data  | 2015-02-29 1 pm |
|    2    |   jack   |  some data  | 2015-02-29 2 pm |
|    3    |   john   |  some data  | 2015-02-29 3 pm |
|    4    |   bill   |  some data  | 2015-02-29 4 pm |
+---------+----------+-------------+-----------------+

Table with john's session
WHERE username=".Session::get('username')."
+---------+----------+-------------+-----------------+
| task_id | username |  some_data  |    some_time    |
+---------+----------+-------------+-----------------+
|    1    |   john   |  some data  | 2015-02-29 1 pm |
|    3    |   john   |  some data  | 2015-02-29 3 pm |
+---------+----------+-------------+-----------------+

I think it is because you are missing single quotes.When you pass a string value into an sql query statement you have to put single quotes. For example,

SELECT tb_list.* FROM tb_list WHERE myusername = '".Session::get('username')."';

Try this one.

return " WHERE username = '".Auth::user()->username."' ";

这个解决了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM