如何从userid等于会话变量的数据库中选择数据

时间:2019-05-09 08:54:43

标签: php mysql sql

我正在尝试使用已定义的会话变量来选择一行,但是当我尝试它时会出现错误:

  

解析错误:语法错误,意外的''(T_ENCAPSED_AND_WHITESPACE),   期待'-'或标识符(T_STRING)或变量(T_VARIABLE)或   第9行的viewmybookings.php中的数字(T_NUM_STRING)

我尝试将会话变量定义为PHP变量并使用PHP变量,但是它仍然不起作用

<?php
//first connect to the the database via your connection insert file
  include'db.php';
    $sql = "SELECT lesson.LessonName,lesson.LessonType,bookingtable.LessonDate,bookingtable.LessonStartTime,bookingtable.Duration,bookingtable.Statues FROM lesson
JOIN bookingtable
ON bookingtable.LessonID=lesson.Id
JOIN users
ON users.UserID = bookingtable.UserID
WHERE users.UserFirstName = <?php $_SESSION['UserID']?>";
//line 9 is the last line
?>

2 个答案:

答案 0 :(得分:-1)

您不需要打开PHP标记,因为您已经在PHP语句中。您需要做的就是将其附加到查询中。

<?php
//first connect to the the database via your connection insert file
include 'db.php';
$sql = "SELECT lesson.LessonName,lesson.LessonType,bookingtable.LessonDate,bookingtable.LessonStartTime,bookingtable.Duration,bookingtable.Statues FROM lesson
JOIN bookingtable
ON bookingtable.LessonID=lesson.Id
JOIN users
ON users.UserID = bookingtable.UserID
WHERE users.UserFirstName = " . $_SESSION['UserID'];
//line 9 is the last line
?>

此查询开放了SQL注入功能(极不可能有人猜到您的会话ID,但有可能),您可以避免使用准备好的语句。

答案 1 :(得分:-1)

您可以像这样简单地在查询中使用任何变量:

$userId = $_SESSION['UserID'];
 $sql = "SELECT lesson.LessonName,lesson.LessonType,bookingtable.LessonDate,bookingtable.LessonStartTime,bookingtable.Duration,bookingtable.Statues FROM lesson
JOIN bookingtable
ON bookingtable.LessonID=lesson.Id
JOIN users
ON users.UserID = bookingtable.UserID
WHERE users.UserFirstName = '$userId'";

请注意SQL注入。