我正在尝试学习如何在 MySQL 中使用变量:
$query = "
SET @myid = '1234';
SELECT * FROM `table1` WHERE `id` = @myid;
";
但是我在第 1 行遇到语法错误。
- 我看过手册,它说这是正确的语法。
- 我也搜索了堆栈,但大多数问题都是基于 存储过程。
MySQL 变量是否仅限于存储过程?如果不是,我做错了什么?
最佳答案
使用 mysqli_multi_query()
- > http://php.net/manual/en/mysqli.multi-query.php
- > Cannot figure out how to run a mysqli_multi_query and use the results from the last query
尝试在查询中使用内联变量会在第 1 行引发语法错误。谢谢 Marc B。
SET @myid = '<?php echo $myid; ?>';
SELECT t.*,
CASE WHEN m.`dob` BETWEEN @uDateStart AND @uDateEnd
etc...
我的解决方案是像这样使用 mysqli::multi_query
或 mysqli_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
防止返回不需要的结果集。
关于php - 在外部存储过程中使用 MySQL 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32573234/