内部加入Where子句?

时间:2013-01-13 03:33:31

标签: php mysql inner-join

$InnerJoinQuery = $STD->query("
        SELECT Users.ID, Users.Username, Users.Password, UserInformation.LastName, UserInformation.Firstname, UserInformation.DOB
        FROM Users AS Users 
        INNER JOIN UserInformation AS UserInformation 
        ON Users.ID = UserInformation.UserID WHERE Users.Username=".$_SESSION['real_name']."");
        $InnerJoinArray = $InnerJoinQuery->fetch_array(MYSQLI_ASSOC);

My Above代码导致错误。它可以达到WHERE条款的目的。

WHERE Users.Username=".$_SESSION['real_name']."

我怎样才能将这种情绪融入我的内心世界?

更新:

$InnerJoinQuery = $STD->query("
        SELECT Users.ID, Users.Username, Users.Password, UserInformation.LastName, UserInformation.Firstname, UserInformation.DOB
        FROM Users
        INNER JOIN UserInformation
        ON Users.ID = UserInformation.UserID WHERE Users.Username = '".$_SESSION['real_name']."'");
        $InnerJoinArray = $InnerJoinQuery->fetch_array(MYSQLI_ASSOC);



        $_SESSION['UID'] = $InnerJoinArray['ID'];
        $_SESSION['Password'] = $InnerJoinArray['Password'];
        $_SESSION['Firstname'] = $InnerJoinArray['Firstname'];
        $_SESSION['LastName'] = $InnerJoinArray['LastName'];
        $_SESSION['DOB'] = $InnerJoinArray['DOB'];
            print_r($_SESSION);

返回:

  

数组([real_name] => inhumaneslayer [密码] => [UID] => [名字] => [姓名] => [DOB] =>)

这不是预期的。

当我将查询更改为:

$InnerJoinQuery = $STD->query("
        SELECT Users.ID, Users.Username, Users.Password, UserInformation.LastName, UserInformation.Firstname, UserInformation.DOB
        FROM Users
        INNER JOIN UserInformation
        ON Users.ID = UserInformation.UserID WHERE Users.Username = 'inhumaneslayer'");

我得到了预期的结果:

  

数组([real_name] => inhumaneslayer [密码] => PASSWORDHIDDEN [UID] => 5 [名字] => xx [姓名] => xx [DOB] => DOBHIDDEN)

预期。

我在更改SQL之前unset($_SESSION);取消了会话

2 个答案:

答案 0 :(得分:2)

您必须将字符串括在引号中:

... Users.Username='".$_SESSION['real_name']."'")

此外 - 您需要正确地转义变量。您将如何做到这一点 - 取决于您使用的数据库库。在你的情况下,它是http://php.net/manual/en/mysqli.real-escape-string.php

... Users.Username='". $STD->real_escape_string($_SESSION['real_name']) ."'")

但更好 - 学习如何使用准备好的陈述http://php.net/manual/en/mysqli.prepare.php

$stmt = $STD->query("
        SELECT Users.ID, Users.Username, Users.Password, UserInformation.LastName, UserInformation.Firstname, UserInformation.DOB
        FROM Users AS Users 
        INNER JOIN UserInformation AS UserInformation 
        ON Users.ID = UserInformation.UserID WHERE Users.Username=?");

$stmt->bind_param("s", $_SESSION['real_name']);

$stmt->execute();
$result = $stmt->get_result();

$InnerJoinArray = $result->fetch_array();

答案 1 :(得分:-1)

你忘记了字符串周围的(单/双)引号(你正在寻找一个字符串,而不是整数?)

尝试:".... WHERE Users.Username='".$_SESSION['real_name']."'")

否则,你的方式,它会搜索

WHERE Users.Username=some_string(而非Users.Username='some_string')将返回错误,因为some_string是一个字符串,需要用引号括起来


如果仍然没有结果:

尝试将您的查询放入变量$query = "SELECT Users .....";

然后echo $query看看你的$ _SESSION变量实际产生了什么。在不知情的情况下,我无能为力。