msqli_query中的$ _SESSION变量

时间:2014-05-13 17:33:05

标签: php variables session

我试图在mqsli_query语句中使用会话变量,但它不起作用

$result = mysqli_query($link, 'SELECT book_ID, Title, username as author from users,books
here users.user_ID = books.user_ID and username = "{$_SESSION['sess_username']}"' );

我尝试使用username =""的实际值。它的工作原理意味着查询很好。当我尝试使用会话变量

时,它不起作用

当用户名设置为实际值时有效的示例代码:

$result = mysqli_query($link, 'SELECT book_ID, Title, username as author from users,books
here users.user_ID = books.user_ID and username = "kllew"' );

2 个答案:

答案 0 :(得分:1)

"正确"这里的方法是预备语句。您再也不需要将字符串连接到SQL查询中或担心引号。

$query = $link->prepare('SELECT book_ID, Title, username as author from users,books
    where users.user_ID = books.user_ID and username = ?');
$books = array();

if($query){
    // Bind the value to the `?`
    $query->bind_param('s', $_SESSION['sess_username']);
    $query->execute();
    // These variables will be created and populated with your values
    $query->bind_result($book_ID, $title, $author);
    while($query->fetch()){
        // Each time `fetch()` is, called, the variables will be
        // automagically updated with the next row's value
        // This while loop will run for each row, then stop
        $books[] = array(
            'book_ID' => $book_ID,
            'title' => $title,
            'author' => $author
        );
    }
}
else{
    die($link->error);
}

var_dump($books);

DOCS:http://www.php.net/manual/en/mysqli.prepare.php

编辑:如果你安装了mysqlnd驱动程序(通常称为php-mysqlnd),那么你可以这样做:

$query = $link->prepare('SELECT book_ID, Title, username as author from users,books
    where users.user_ID = books.user_ID and username = ?');
$books = array();

if($query){
    // Bind the value to the `?`
    $query->bind_param('s', $_SESSION['sess_username']);
    $query->execute();

    // This allows you to use `fetch_array` like if you had used `mysqli_query`
    $result = $query->get_result();
    $books = $result->fetch_all(MYSQLI_ASSOC);
}
else{
    die($link->error);
}

var_dump($books);

答案 1 :(得分:0)

请尝试以下方法:(将会话置于var中,并更改使用单引号的方式。

$session = $_SESSION['sess_username'];
$result = mysqli_query($link, "SELECT book_ID, Title, username as author from users,books
here users.user_ID = books.user_ID and username = '$session'" );