MySQL存储过程返回0行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL存储过程返回0行相关的知识,希望对你有一定的参考价值。

当我在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中使用它?

答案

问题是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`;" );

编辑:另见:

使用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, "&nbsp;";
      }
      $result->close();
      if( $mysqli->more_results() ) echo "<br/>";
    }
  } while( $mysqli->next_result() );
}
$mysqli->close();

以上是关于MySQL存储过程返回0行的主要内容,如果未能解决你的问题,请参考以下文章

MYSQL的存储过程如何返回查询到的行数据?

图解MySql命令行创建存储过程

mysql 存储过程中update影响行数为0,回滚

MySQL_基础_存储过程和函数

MySQL位置选择查询在存储过程中返回0

mysql里边,存储过程之间相互调用