douxun4860 2014-10-15 23:45
浏览 32
已采纳

在mysqli查询中使用会话用户名为“WHERE”[关闭]

I know I am doing something wrong but I really would like to know what it is. I can echo the username of the session loggedin user using <?php echo $_SESSION['username']; ?>but I don't know why it doesn't work when I try to query database using the same technique. my codes below

I include this in the page

<?php session_start(); $username=$_SESSION['username']; ?>

and here is the code that was suppose to display firstname and user_id of the sessions logged in user

    <?php
$conn = new mysqli('localhost', 'root', 'browser', 'test');

if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

$username = '$username';

$sql = "SELECT `user_id`, `firstname` FROM `members` WHERE `username`='$username'"; 
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    echo '<br /> user_id: '. $row['user_id']. ' - firstname: '. $row['firstname'];
  }
}
else {
  echo '0 results';
}

$conn->close();
?>
  • 写回答

1条回答 默认 最新

  • dongqian6554 2014-10-15 23:47
    关注
    $username = '$username';
    

    PHP variables inside single-quotes are not expanded. So now your variable is the literal string '$username', which undoubtedly won't match any user in your database.

    You probably need to set $username = $_SESSION['username']; in your second PHP script.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题