【问题标题】:Loading current user from database从数据库加载当前用户
【发布时间】:2025-12-16 10:30:02
【问题描述】:

所以我有一个名为 realtimeusage 的表,它包含 ID、KWH、UnitValue、AccessTIME 我只想通过他的“id”获取当前用户对我的代码的任何建议的使用情况

<?php
session_start();
require_once('connect.php');

$_SESSION['id'] = $id;

// For display  Current user realtimeusage 
$displayquery = "SELECT * ";
$displayquery .= "FROM realtimeusage WHERE `id` = '".$_SESSION['id']."'";

$displayresult = mysqli_query($connection, $displayquery);
if (!$displayresult){
    die("database query failed");
}

?>

要获取数据的表:

<table>
    <thead>
        <tr>
            <th> AccountID</th>
            <th> KWH</th>
            <th>UnitValue</th>
            <th>AccessTIME</th>
        </tr>
    </thead>
    <tbody>
        <?php
            while ($rows= mysqli_fetch_assoc($displayresult)) {
         ?>
        <!--id-->
        <td><?php echo $rows["ID"]; ?></td>

        <!--User name-->
        <td><?php echo $rows["KWH"]; ?></td>

        <!--Full name-->
        <td><?php echo $rows["UnitValue"]; ?></td>

        <!-- Roles-->
        <td><?php echo $rows["AccessTIME"]; ?></td>

    </tbody>
    <?php } ?>
</table>

当我运行此代码时,它会在表格中显示所有使用情况

<?php
session_start();
require_once('connect.php');

$username = $_SESSION['username'];
$roles = $_SESSION['roles'];


// For display realtimeusage
$displayquery = "SELECT * ";
$displayquery .= "FROM realtimeusage";

$displayresult = mysqli_query($connection, $displayquery);
    if (!$displayresult){
        die("database query failed");
    }

?>

【问题讨论】:

  • 您遇到了什么问题?
  • 它不工作我得到一个空表
  • $id 定义为..是什么?
  • 您确定$id 就是您认为的那样,如果您在数据库上手动运行该查询,您会得到结果吗?
  • 您没有$id$connection 变量。您还应该使用prepared statements 来防止SQL 注入。

标签: php mysql localhost


【解决方案1】:

你从哪里得到 id 的值?我猜 id 在 $_SESSION['id'] 中,如果用户已登录,并且要使用该 id,您需要将赋值语句更改为

$id=$_SESSION['id'];

并在查询中使用 $id

$displayquery .= "FROM `realtimeusage` WHERE `id` = '".$id."'";

【讨论】:

  • 还是空表:(
  • 检查你是否在会话中获取 id... echo $_SESSION['ID'] ;