简体   繁体   English

MySQL存储过程:无法从PHP代码运行

[英]MySQL stored procedure: can't run from PHP code

I have the below stored procedure to check the user name availability 我有以下存储过程来检查用户名可用性

DELIMITER $$;

DROP PROCEDURE IF EXISTS tv_check_email$$

CREATE PROCEDURE tv_check_email (IN username varchar(50))
BEGIN
  select USER_ID from tv_user_master where EMAIL=username;
END$$

DELIMITER ;$$

When I run this from my MySQL front end tool, it is works just fine: 当我从我的MySQL前端工具运行它时,它工作得很好:

call tv_check_email('shyju@techies.com')

But when trying to execute from the PHP page, I get an error like 但是当试图从PHP页面执行时,我得到一个错误

"PROCEDURE mydatabase.tv_check_email can't return a result set in the given context"

I am sure that my PHP version is 5.2.6. 我确信我的PHP版本是5.2.6。

You need to bind your result into an OUT parameter. 您需要将结果绑定到OUT参数。

See the mysql docs on stored procedures 请参阅存储过程的mysql文档

mysql> delimiter //

mysql> CREATE PROCEDURE simpleproc (OUT param1 INT)
    -> BEGIN
    ->   SELECT COUNT(*) INTO param1 FROM t;
    -> END;
    -> //
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;

mysql> CALL simpleproc(@a);
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @a;
+------+
| @a   |
+------+
| 3    |

+------+ + ------ +

It looks like if you use the mysqli PHP library you can actually retrieve your result set without having to use an OUT variable and another query to retrieve your value. 看起来如果使用mysqli PHP库,您实际上可以检索结果集,而无需使用OUT变量和另一个查询来检索您的值。 This article covers the details: 本文介绍了详细信息:

http://amountaintop.com/php-5-and-mysql-5-stored-procedures-error-and-solution-qcodo http://amountaintop.com/php-5-and-mysql-5-stored-procedures-error-and-solution-qcodo

Cody is not 100% right. 科迪并非100%正确。 You can bind your resulting return columns and return select data from within a stored procedure. 您可以绑定生成的返回列并从存储过程中返回选择数据。

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$stmt = $mysqli->prepare("call tv_check_email(?)");
$stmt->bind_param('s', "shyju@techies.com");
$stmt->execute();

$stmt->bind_result($userid);

while ($stmt->fetch()) {
  printf("User ID: %d\n", $userid);
}

$stmt->close();
$mysqli->close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM