首页 > 解决方案 > 有没有办法在传递 $_SESSION 变量作为参数时从 PHP 调用 mySQL 存储过程?

问题描述

我正在尝试做的事情:

什么有效:

我试过的:

这是用于获取结果并使用与前面提到的相同方法将它们显示在表中的 PHP:我也尝试使用 {} 来传递 $_SESSION 变量。

<?php
$sql = "CALL getStudentDevices(.$_SESSION["studentID"].)"; 
$result = mysqli_query($conn, $sql);  // $conn details omitted

// If selection is not empty
// Create table row for each record selected
if ($result->num_rows > 0) {
     echo "<table> <tr> <th>DeviceID</th> <th>DeviceName</th> </tr>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<tr> <td>".$row["DeviceID"]."</td> <td>".$row["DeviceName"]."</td> </tr>";
     }
     echo "</table>";
} else {
     // If select is empty then
     echo "0 results";
}

$conn->close();
?>

这是存储过程(从 DBMS 调用时可以完美运行):

DELIMITER $$
CREATE DEFINER=`username`@`hostname` PROCEDURE `getStudentDevices`(IN `StudentID` VARCHAR(11))
    READS SQL DATA
SELECT Devices.DeviceID, Devices.DeviceName FROM Accounts
    LEFT JOIN Courses ON Accounts.CourseID = Courses.CourseID
    LEFT JOIN Course_Category cc ON Courses.CourseID = cc.CourseID
    LEFT JOIN Categories ON cc.Category = Categories.Category
    LEFT JOIN Devices ON Categories.Category = Devices.Category
    WHERE Accounts.StudentID = @p0 AND Devices.Available = 1$$
DELIMITER ;

表创建方法在使用 select 语句时有效,但是,当我尝试使用存储过程打开此页面时,没有显示任何内容。整个页面是空白的。请注意,安全不是问题。

标签: phphtmlmysql

解决方案


问题在于您如何构建查询,您正在混合字符串构建样式。而且您缺少参数的引号

老派风格:

$sql = 'CALL getStudentDevices("' . $_SESSION["studentID"] . '")';

变量传递:

$sql = "CALL getStudentDevices(\"{$_SESSION["studentID"]}\")";

推荐阅读