MySQL 存储过程返回 0 行
Posted
技术标签:
【中文标题】MySQL 存储过程返回 0 行【英文标题】:MySQL Stored Procedure returns 0 rows 【发布时间】:2018-08-13 12:23:56 【问题描述】:当我在 phpMyAdmin(SQL 选项卡)中像这样调用过程时,它可以工作:
CALL `test_discount`('022979', 1101, 1, 'W', 100, @p5); SELECT @p5 AS `discount`;
但是,当我像这样在PHP
中调用它时:
$res = $conn->query("CALL `test_discount`('022979', 1101, 1, 'W', 100, @p5); SELECT @p5 AS `discount`;");
我收到语法错误:You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT @p5 AS discount' at line 1
如何让它在 PHP 中工作?
【问题讨论】:
@p5);
@FunkFortyNiner 同样的问题。 SELECT @p5 AS discount
附近的语法错误...
【参考方案1】:
问题是 mysql 不支持单个 query
调用中的多个语句:http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
例如给定以下代码(来自上面的链接):
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$res = $mysqli->query("SELECT 1; DROP TABLE mysql.user");
if (!$res)
echo "Error executing query: (" . $mysqli->errno . ") " . $mysqli->error;
?>
您将收到以下输出:
Error executing query: (1064) You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax
to use near 'DROP TABLE mysql.user' at line 1
解决方案:使用多查询:
$mysqli->multi_query( "CALL `test_discount`('022979', 1101, 1, 'W', 100, @p5); SELECT @p5 AS `discount`;" );
编辑:另见:
PHP + MySql + Stored Procedures, how do I get access an "out" value? http://www.joeyrivera.com/2009/using-mysql-stored-procedures-with-php-mysqlmysqlipdo/使用multi_query
调用过程的例子:
$mysqli = new mysqli( "HOST", "USR", "PWD", "DBNAME" );
$ivalue=1;
$res = $mysqli->multi_query( "CALL myproc($ivalue,@x);SELECT @x" );
if( $res )
$results = 0;
do
if ($result = $mysqli->store_result())
printf( "<b>Result #%u</b>:<br/>", ++$results );
while( $row = $result->fetch_row() )
foreach( $row as $cell ) echo $cell, " ";
$result->close();
if( $mysqli->more_results() ) echo "<br/>";
while( $mysqli->next_result() );
$mysqli->close();
【讨论】:
我如何获得$mysqli->multi_query( "CALL test_discount('022979', 1101, 1, 'W', 100, @p5); SELECT @p5 AS discount;" );
的结果?因为$res->fetch_assoc()
不起作用...
@Borsn 请参阅我在下面提供的链接,您需要使用 store_result。我将使用该链接中的代码更新我的答案以上是关于MySQL 存储过程返回 0 行的主要内容,如果未能解决你的问题,请参考以下文章