从登录的用户中选择数据

时间:2012-02-17 14:44:26

标签: php mysql logged

当用户登录时,我希望他看到他所做的课程和他的结果。

目前我有这个:

<?php
  session_start();
  if(isset($_SESSION['user'])) {

  $query = "SELECT applied_cours, stud_res FROM students";
  $result = mysql_query($query);

    while($student = mysql_fetch_array($result)) {
      echo "<p>" . $student['applied_cours'] . "</p>";
      echo "<p>" . $student['stud_res'] . "</p>";
    }
  }
?>

问题在于,这将显示每个人的所有课程和结果,而不仅仅是来自登录用户。有人知道如何解决这个问题吗?

我使用的表格如下:

username, password, stud_id, studgr_id, applied_cours, stud_res
user1, password1, 6567, 2012_1, timemanagement, satisfactory
user2, password2, 8459, 2012_2, timemanagement, satisfactory
etc.

3 个答案:

答案 0 :(得分:1)

添加where子句

$query = "SELECT applied_cours, stud_res FROM students Where username='$_SESSION[user]'"; 

答案 1 :(得分:0)

如果用户已登录,请将其ID存储在$_SESSION

$_SESSION['user']['id'] = [insert user ID here]; // the stud_id

然后:

$query = 'SELECT applied_cours, stud_res FROM students WHERE stud_id = "'.$_SESSION['user']['id'].'"';

答案 2 :(得分:0)

使用参数化的sql语句,因为你不能信任输入,你永远不应该直接将变量写入语句。

$stmt = $dbh->prepare("SELECT applied_cours, stud_res FROM students WHERE stud_id =  ? ");
$stmt->bindParam(1, $_SESSION['user']['id']);

$stmt->execute();

请在此处阅读:http://php.net/manual/en/pdo.prepared-statements.php