Domanda

I'm trying to use a session variable in a mqsli_query statment but it doesn't work

$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']}"' );

I tried using real values for username = "" and it works so it means that the query is fine. It doesnt work when I try to use session variable

sample code that works when username is set to real value:

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

Soluzione

The "correct" method here is prepared statements. Never again will you need to concat strings into an SQL query or worry about quotes.

$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

EDIT: If you have the mysqlnd driver installed (usually called php-mysqlnd), then you can do this:

$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);

Altri suggerimenti

Try this instead: (put the session in var, and change how you are using single quotes.

$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'" );
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top