php - 从 PHP 调用存储过程,使用 PHP 变量作为 IN 参数

标签 php mysql stored-procedures

我的表格如下所示:

Category Table Sub Category Table

我有一个过程,我试图用它来获取与给定 CategoryName 具有相同 CategoryID 的所有 SubCategoryName:这个:

CREATE PROCEDURE getSubCategory(IN category TEXT) READS SQL DATA
     BEGIN
         SELECT `SubCategoryName` FROM `sub_category` WHERE `CategoryID` = (SELECT `CategoryID` FROM `category` WHERE `CategoryName` = category);
     END

出于某种原因,当我尝试使用 PHP 变量从 PHP 代码调用此过程时,如下所示:

$result = $connection->query($connection->real_escape_string("CALL `jcarillo_db`.getSubCategories(" . $superCategory . ")"));
    // based on that, print the appropriate menu
    if ($result)
    {
        // print an <option> for each row in the result set (remember, $result will have one entry per row!)
        while ($row = $result->fetch_row())
        {
            require_once("argumentParser.php");
            printf('<option name="%sOption" value="%s">%s</option>\n', toCamelCase($row[0]), $row[0], $row[0]);
        }
        // don't forget to free result set!
        $result->close();
    }
    else
    {
        echo "Fetch failed(" . $connection->errno . ")" . $connection->error;
    }

“获取失败”得到回显,而不是结果!然而,由于某种原因,当我尝试从数据库调用相同的存储过程(即通过 phpMyAdmin)时,它起作用了!我到底做错了什么?!?! $connection 设置正确,我知道这一点是因为我尝试从类别表中回显 CategoryNames 可以使用它!

最佳答案

这里的问题是,您尝试使用字符串参数调用该函数,并且在传递该参数时没有让 MySQL 知道它是一个字符串。

试试这个:

$result = $connection->query("CALL `jcarillo_db`.getSubCategories('".$connection->real_escape_string($superCategory)."')");

关于php - 从 PHP 调用存储过程,使用 PHP 变量作为 IN 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26825918/

相关文章:

PHP mkdir - 为什么这是一个无效参数?

MYSQL Select Left Join - 如何使用 2 个不同的 id 从同一个表中获取 2 行?

在 MySQL 查询的 LIMIT 子句中使用占位符时出现 PHP PDO 错误

mysql - 有没有更有效的方法来跟踪没有 child 的 parent 记录?

php - 将 mysql 数据库中的多行存储到一个变量中

php - SQL 计数 不确定如何让它与模型、 View 和 Controller 一起工作

php - laravel 如何指定输入列

function - PLS-00201 - 必须声明标识符 'Stored-Procedure-Name'

mysql - 更新(子查询)设置.....MariaDB(MySQL)中的表达式

mysql - 使用过程创建备份表