打印登录用户数据以匹配登录SESSION

时间:2017-05-18 07:31:27

标签: php mysql session pdo user-profile

我是PHP和Mysql的新手我正在为我的作业编写购物网站,

我的登录,注册和数据库已启动并运行,现在我处于需要执行用户配置文件页面的阶段,该页面需要从数据库中提取数据,

首先我有这个代码,因为它会从我的表中提取所有内容,

  <?php
      $sql = 'SELECT * from assignment2';
      $result = $conn->query($sql);
      $rows = $result->fetchAll(PDO::FETCH_ASSOC);

      if(count($result)) {
          echo '<table><tr>';
          //Heading
          foreach ($rows[0] as $columnName => $value) {
              echo '<th>' . $columnName . '</th>' ;
          }
          echo '</tr>';
          foreach ($rows as $row) {
              echo '<tr>';
              foreach ($row as $value) {
                  echo '<td>' . $value . '</td>';
              }
              echo '<tr>';
          }
          echo '</table>';
        }
        ?>

但我的问题是如何使它只拉出与登录SESSION匹配的那个

这是我的会话代码

<?php

session_start();

require '../ppuyakul/php/db_conn.php';

if( isset($_SESSION['user_id']) ){

    $records = $conn->prepare('SELECT id,username,password FROM assignment2 WHERE id = :id');
    $records->bindParam(':id', $_SESSION['user_id']);
    $records->execute();
    $results = $records->fetch(PDO::FETCH_ASSOC);

    $user = NULL;

    if( count($results) > 0){
        $user = $results;
    }

}
?>

提前非常感谢,期待一些不错的答案^^“

1 个答案:

答案 0 :(得分:1)

如果id = $ _SESSION [&#39; user_id&#39;]($sql = 'SELECT * from assignment2';

,只需使用WHERE检查扩展您的SQL查询($sql = 'SELECT * from assignment2 WHERE id = '.$_SESSION['user_id'];

//的foreach

$sql = 'SELECT * from assignment2 WHERE id = '.$_SESSION['user_id'];
$result = $conn->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);

  if(count($result)) {
      echo '<table><tr><th>Id</th><th>Fullname</th><th>Username</th></tr>';
      foreach ($rows as $row) {
          echo '<tr>';
          echo '<td>'.$row["id"].'</td>';
          echo '<td>'.$row["fullname"].'</td>';
          echo '<td>'.$row["username"].'</td>';
          echo '<tr>';
      }
      echo '</table>';
    }