简体   繁体   English

使用PHP将会话变量添加到MYSQL查询中

[英]Adding session variable into MYSQL query using PHP

Im trying to pass two variables into a mysql query, and its getting stuck when passing the session variable in below: 我试图将两个变量传递给一个mysql查询,并在下面传递会话变量时遇到困难:

$check = mysql_query("SELECT * 
                      FROM Clients 
                      WHERE Username = '$new_username' 
                      AND Username != '$_SESSION['Username']'") or die(mysql_error()); 

Any tips? 有小费吗? Thanks in advance. 提前致谢。

It is because your single quotes '$_SESSION['Username']' have been ended by the value in the session. 这是因为你的单引号'$_SESSION['Username']'已经被会话中的值结束了。 Changing this to '" . $_SESSION['Username'] . "' will solve the problem. 将此更改为'" . $_SESSION['Username'] . "'将解决问题。

This will work but this is VERY, VERY BAD : 这将工作,但这非常,非常糟糕

$check = mysql_query("
    SELECT * 
    FROM  Clients 
    WHERE Username = '$new_username' 
    AND   Username != '{$_SESSION['Username']}'
") or die(mysql_error());

This too shall work and recommended way of doing it: 这也是可行的,也是推荐的做法:

$check = mysql_query("
    SELECT * 
    FROM  Clients 
    WHERE Username  = '" . mysql_real_escape_string($new_username) . "' 
    AND   Username <> '" . mysql_real_escape_string($_SESSION['Username']) . "'
") or die(mysql_error());

Why no one say about "text text $array[key] text" syntax? 为什么没有人说“text text $ array [key] text”语法?

SELECT * 
FROM  Clients 
WHERE Username = '$new_username' 
AND   Username != '$_SESSION[Username]'

When you embed arrays in to strings, you have to seperate them by concatenating them or using curly braces. 将数组嵌入到字符串中时,必须通过连接它们或使用花括号来分隔它们。

$string = "text text {$array['key']} text";

or 要么

$string = "text text " . $array['key'] . " text";

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

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