php - 有没有办法在传递 $_SESSION 变量作为参数时从 PHP 调用 mySQL 存储过程?
问题描述
我正在尝试做的事情:
- 我需要调用存储在 mySQL 服务器上的PHP 存储过程getStudentDevices() 。
- 它需要一个参数@p0。
- 我想使用 $_SESSION 变量studentID提供该参数。
什么有效:
- 我可以从 phpMyAdmin 调用存储过程,它提供了正确的结果。所以这不是程序的问题。
- 我可以使用不同的select 语句从 PHP 查询数据库,结果显示我想要的方式,所以我认为从 PHP 连接到数据库没有问题。
我试过的:
这是用于获取结果并使用与前面提到的相同方法将它们显示在表中的 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 语句时有效,但是,当我尝试使用存储过程打开此页面时,没有显示任何内容。整个页面是空白的。请注意,安全不是问题。
解决方案
问题在于您如何构建查询,您正在混合字符串构建样式。而且您缺少参数的引号
老派风格:
$sql = 'CALL getStudentDevices("' . $_SESSION["studentID"] . '")';
变量传递:
$sql = "CALL getStudentDevices(\"{$_SESSION["studentID"]}\")";
推荐阅读
- android - 如何设计 tabitems,而不将它们放在 .xml 文件中
- python - 如何制作具有一定滞后的两个时间序列的相关图
- reactjs - 如何遍历firebase中的所有节点
- javascript - 如何将多变量定点组合器翻译成严格的语言?
- javascript - Javascript:通过函数循环遍历两个数组并在数组中求和元素
- c# - 将用户添加到表并使用用户 ID,同时在用户注册时将数据添加到第二个表
- c# - 比较具有像素差异的位图
- react-native - 如何从值从 tcomb-form-native 设置状态
- python - 在列的百分比结构中汇总交叉表中的列?
- ssrs-2012 - 如何让报告分组查看整数而不是前两位数?