Php $\ msqli\ U查询中的会话变量
我试图在mqsli_查询语句中使用会话变量,但它不起作用Php $\ msqli\ U查询中的会话变量,php,variables,session,Php,Variables,Session,我试图在mqsli_查询语句中使用会话变量,但它不起作用 $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 = "{$_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"' );
试试这个:将会话放在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'" );
这里正确的方法是准备语句。您再也不需要将字符串压缩到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);
文件:
编辑:如果安装了通常称为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);
语法高亮显示您的问题抱歉,我不明白。“sess_username”是黑色的那部分?我对这个很陌生。试着用一下。我也试过了。不起作用。谢谢你的回答。你的会话变量设置正确了吗?@alex:你忘了在SQL查询中用引号括起来了。另外,你可以这样做:选择。。。用户名=“{$\u SESSION['sess\u username']}”。哦,糟糕的是,我甚至没有注意到,thanks@alex很抱歉,我对这一点很陌生,你把会话放在var中是什么意思。。像这样$_会话[$var]?我是否继续使用$result=msqli\u query$link,$query@user3632739:No.$query->execute运行您的查询。调用$query->fetch时,结果将存储在$book\u ID、$title和$author中。准备好的语句有点不同。那么我可以在数组中存储$book_ID、$title和$author吗?怎样我需要将它们存储在一个数组中,因为我有将它们作为数组获取并显示的代码。您的查询返回多少行?如果只有一个,则可以执行:$result=array$查询->绑定结果$result['book\u ID'],$result['title'],$result['author']$query->fetch@user3632739:您只需将它们添加到while循环中的数组中即可。