【问题标题】:Using MySQL variables in outside stored procedures在外部存储过程中使用 MySQL 变量
【发布时间】:2015-12-10 22:51:41
【问题描述】:

我正在尝试学习如何在 MySQL 中使用变量:

$query = "
    SET @myid = '1234';
    SELECT * FROM `table1` WHERE `id` = @myid;
";

但我在第 1 行遇到语法错误。

  • 我查看了手册,它指出这是正确的语法。
  • 我也搜索过堆栈,但大多数问题都是基于 存储过程。

MySQL 变量是否仅限于存储过程?如果不是我做错了什么?

【问题讨论】:

标签: php mysql sql variables stored-procedures


【解决方案1】:

使用 mysqli_multi_query()

尝试在查询中使用内联变量会在第 1 行引发语法错误。谢谢 Marc B。

SET @myid = '<?php echo $myid; ?>';
SELECT t.*,
    CASE WHEN m.`dob` BETWEEN @uDateStart AND @uDateEnd
    etc...

我的解决方案是像这样使用mysqli::multi_querymysqli_multi_query

$this -> db -> multi_query($sql);
$i = 0;
$querySelect = 1; //query 1
do{
    if($result = $this -> db -> store_result()) {
        if($i === $querySelect) {
            while($row = mysqli_fetch_array($result)) {
                $data[] = $row;
            }
            mysqli_free_result($result);
        }
    }
    $i++;
} while($this -> db -> more_results() && $this -> db -> next_result());

$querySelect 防止返回不需要的结果集。

【讨论】:

    猜你喜欢
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2023-04-05
    • 2016-07-19
    • 2012-10-08
    相关资源
    最近更新 更多