简体   繁体   English

尝试从其中user_id = $ _SESSION ['id']的数据库表中选择时出错

[英]Error when trying to select from a database table where user_id = $_SESSION['id']

I've seen that there are many posts about this error, but I can't find an answer for my particular problem. 我已经看到有很多关于此错误的文章,但是找不到针对我特定问题的答案。 I'm trying to show a table for the user, but only if is logged in, and only if the table row is added by that particular user.So, i'm trying tu use this line: 我试图为用户显示一个表,但是只有在登录后并且该表行是由该特定用户添加的情况下,因此,我试图使用此行:

$sql = "SELECT * FROM data WHERE id_user = $_SESSION['id']";
$result = mysqli_query($connect, $sql);

And I get this error: 我得到这个错误:

" syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)" “语法错误,意外”(T_ENCAPSED_AND_WHITESPACE),期望为“-”或标识符(T_STRING)或变量(T_VARIABLE)或数字(T_NUM_STRING)”

Also, i tried 另外,我尝试了

$sql = "SELECT * FROM 'data' WHERE 'id_user' = '$_SESSION['id']'";

Note the ' ' around table name and variables 注意表名和变量周围的''

What to change so that the syntax is good? 进行哪些更改才能使语法良好?

Don't do it like that, use a prepared statement: 不要那样做,使用准备好的语句:

$sql = "SELECT * FROM data WHERE id_user = ?";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "i", $_SESSION['id']);
mysqli_stmt_execute($stmt);

More info can be found here: https://secure.php.net/manual/en/mysqli.prepare.php 更多信息可以在这里找到: https//secure.php.net/manual/en/mysqli.prepare.php

It takes some getting used to, and it might be a little more verbose (you could wrap that in your own class or functions), but it will be vastly safer and more portable. 这需要一些时间来适应,并且可能会有些冗长(您可以将其包装在您自己的类或函数中),但是它将更加安全和可移植。

Not to mention you can brag to your friends that you use prepared statements by default! 更不用说您可以吹嘘您的朋友默认情况下使用准备好的语句!

change your query as: 将查询更改为:

$sql = "SELECT * FROM data WHERE id_user = ". $_SESSION['id'];

This may work for you as of now, but you have to change your query as your query is open for SQL injection. 到目前为止,这可能对您有用,但是由于您的查询已打开以进行SQL注入,因此您必须更改查询。

Use prepared statement to build your query. 使用准备好的语句来构建您的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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