使用 MySQLi 从 PHP 调用 MySQL 存储函数时发生致命错误

发布于 2024-10-22 04:58:52 字数 3926 浏览 1 评论 0原文

服务器详细信息:
PHP v5.3.5
使用 MySQLi 库客户端 api 版本:mysqlnd 5.0.7-dev - 091210 - $修订版:304625 $
MySQL Server v5.5.9

我在 MySQL 中有一个名为 f_get_owner_locations( _in int ) 的存储函数。它构造一个文本变量,用于保存特定所有者拥有的任何公寓的位置。 如果我从 MySQL 命令行运行 a

SELECT f_get_owner_locations( 3 );  

,它会执行它应该执行的操作并返回一行:

+----------------------------+
| f_get_owner_locations( 3 ) |
+----------------------------+
| A-01                       |
+----------------------------+

但是,每当我尝试使用 MySQLi 库通过 PHP 运行它时:

$sql = "SELECT f_get_owner_locations( 3 )";
$location = $GLOBALS['db']->fetch( $sql );

我收到此错误:

Fatal error: Call to a member function fetch_field() on a non-object 
in ~/kernel/Database.php on line 328

该行指的是:

/**
 * Binds results from a returning SQL statement to an array we can 
 * loop through.
 * 
 * @param   $statement  Statement object we're binding from.
 * @return  Array of values being returned.
 * @since   0.1
 */
private final function _bindResult( $statement )
{
    $results = NULL;
    $bind = array( );

    //Get the result set, so we can loop through the fields.
    $result = $statement->result_metadata( );
    //Loop through the fields and get a reference to each.
    while( $column = $result->fetch_field() ) //<=<=<=LINE 328
        $bind[] = &$results[$column->name];
    //Do the actual binding.
    call_user_func_array( array( $statement, 'bind_result'), $bind );

    //Free the memory since we already have the result.
    $result->free_result();

    return $results;
} //_bindResult

请记住,当 SQL 语句不涉及函数调用时,它不会失败。即这有效:

$sql = "SELECT `id` FROM `owners`";
$owners = $GLOBALS['db']->fetch( $sql );

但是一旦我添加了将他们拥有的公寓放入其中的需要(并且该语句也通过MySQL命令行工作):

$sql = "SELECT `id`, f_get_owner_locations(`id`) FROM `owners`";
$owners = $GLOBALS['db']->fetch( $sql );

它给了我关于在非-上调用成员函数的错误目的。

我很困惑。在 while 循环之前对 $result 执行 var_dump,在我的 _bindResults 方法中为我提供了 1 个正确的转储,然后停止并出现该错误。

object(mysqli_result)#11 (5) {
  ["current_field"]=>
  int(1)
  ["field_count"]=>
  int(1)
  ["lengths"]=>
  NULL
  ["num_rows"]=>
  int(0)
  ["type"]=>
  int(1)
}

注意:对 f_get_owner_locations 的调用是该选择列表上的第二个字段,因此它没有存储正确的字段计数,尽管它需要循环到正确数量的字段。

任何绕过这个小障碍的建议或确认这是 MySQLi 库中的错误或我的绑定代码的问题将不胜感激。

更新: 以下代码:

mysql_connect( ... );
mysql_query( "select f_get_owner_locations(3)" );
die( mysql_error() );

给了我这个输出:

FUNCTION f_get_owner_locations does not exist.

我更想知道这是否只是 PHP/MySQLi 方面的失败而不是我的失败?

更新2:
根据要求,用于创建该函数的代码:

drop function if exists f_get_owner_locations;
delimiter |
create function f_get_owner_locations( _in int )
returns text deterministic
begin
    declare _output text default "";
    declare _location varchar(255);
    declare _count int default 0;
    declare _done int default 0;
    declare _cursor cursor for 
        select
            condos.location
        from
            owners left join
            condo_owners on owners.id = condo_owners.owner left join
            condos on condo_owners.condo = condos.id
        where
            owners.id = _in;
    declare continue handler for not found set _done = 1;

    open _cursor;

    repeat
        fetch _cursor into _location;
        set_count = _count + 1;
        set_output = concat( _output, ", ", _location );
    until _done end repeat;

    set _count = _count - 1;

    close _cursor;

    set _output = trim( leading ", " from _output );
    set _output = substring( _output from 1 for (_count * 6) );
    set _output = trim( trailing ", " from _output );
    return _output;
end;|
delimiter ;

经过一些重构,可能会更干净一些,但这就是我所使用的。

Server details:
PHP v5.3.5
Using MySQLi library client api version: mysqlnd 5.0.7-dev - 091210 - $Revision: 304625 $
MySQL Server v5.5.9

I have a stored function in MySQL called f_get_owner_locations( _in int ). It constructs a text variable that holds the locations of whichever condos a specific owner owns.
If I run a

SELECT f_get_owner_locations( 3 );  

from the MySQL command line, it does what it's supposed to do and returns one row:

+----------------------------+
| f_get_owner_locations( 3 ) |
+----------------------------+
| A-01                       |
+----------------------------+

However, whenever I try and run it through PHP using the MySQLi library as such:

$sql = "SELECT f_get_owner_locations( 3 )";
$location = $GLOBALS['db']->fetch( $sql );

I get this error:

Fatal error: Call to a member function fetch_field() on a non-object 
in ~/kernel/Database.php on line 328

That line refers to this:

/**
 * Binds results from a returning SQL statement to an array we can 
 * loop through.
 * 
 * @param   $statement  Statement object we're binding from.
 * @return  Array of values being returned.
 * @since   0.1
 */
private final function _bindResult( $statement )
{
    $results = NULL;
    $bind = array( );

    //Get the result set, so we can loop through the fields.
    $result = $statement->result_metadata( );
    //Loop through the fields and get a reference to each.
    while( $column = $result->fetch_field() ) //<=<=<=LINE 328
        $bind[] = &$results[$column->name];
    //Do the actual binding.
    call_user_func_array( array( $statement, 'bind_result'), $bind );

    //Free the memory since we already have the result.
    $result->free_result();

    return $results;
} //_bindResult

Keep in mind it doesn't fail when the SQL statement doesn't involve a function call. i.e. This works:

$sql = "SELECT `id` FROM `owners`";
$owners = $GLOBALS['db']->fetch( $sql );

But as soon as I add in the need to get the condos they own into it (and this statement works through the MySQL command line as well):

$sql = "SELECT `id`, f_get_owner_locations(`id`) FROM `owners`";
$owners = $GLOBALS['db']->fetch( $sql );

It gives me that error about call to a member function on a non-object.

I'm stumped. Doing a var_dump on $result right before the while loops, in my _bindResults method gives me 1 proper dump, and then stops and that error is there.

object(mysqli_result)#11 (5) {
  ["current_field"]=>
  int(1)
  ["field_count"]=>
  int(1)
  ["lengths"]=>
  NULL
  ["num_rows"]=>
  int(0)
  ["type"]=>
  int(1)
}

Note: The call to f_get_owner_locations is the 2nd field on that select list, so it's not storing the right field count, despite saying that it needs to loop to the correct amount of fields.

Any suggestions to get around this little road block or a confirmation that this is a bug within the MySQLi library or a problem with my binding code would be much appreciated.

UPDATE:
The following code:

mysql_connect( ... );
mysql_query( "select f_get_owner_locations(3)" );
die( mysql_error() );

Gave me this output:

FUNCTION f_get_owner_locations does not exist.

I'm more wondering if this is just a failure on PHP/MySQLi's part than mine?

UPDATE 2:
As requested, the code used to create the function:

drop function if exists f_get_owner_locations;
delimiter |
create function f_get_owner_locations( _in int )
returns text deterministic
begin
    declare _output text default "";
    declare _location varchar(255);
    declare _count int default 0;
    declare _done int default 0;
    declare _cursor cursor for 
        select
            condos.location
        from
            owners left join
            condo_owners on owners.id = condo_owners.owner left join
            condos on condo_owners.condo = condos.id
        where
            owners.id = _in;
    declare continue handler for not found set _done = 1;

    open _cursor;

    repeat
        fetch _cursor into _location;
        set_count = _count + 1;
        set_output = concat( _output, ", ", _location );
    until _done end repeat;

    set _count = _count - 1;

    close _cursor;

    set _output = trim( leading ", " from _output );
    set _output = substring( _output from 1 for (_count * 6) );
    set _output = trim( trailing ", " from _output );
    return _output;
end;|
delimiter ;

Granted with a bit of refactoring that could could be a small bit cleaner, but that's what I used.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

摇划花蜜的午后 2024-10-29 04:58:52

MySQL 存储过程可以返回多个结果集,其中最后一个结果集是您感兴趣的实际数据。mysqli 正确执行的几件事之一就是支持多个结果集。

尝试检查 mysqli::more_results 。另请检查手册页上的免责声明 mysqli::store_result< /code>关于 mysqli 如何处理多个结果集,其中一个结果集可能没有数据。您最终将使用 mysqli_result< /a> 类而不是 mysqli_stmt

MySQL stored procedures can return multiple result sets, where the last result set is the actual data you're interested in. One of the few things that mysqli does correctly is support multiple result sets.

Try checking mysqli::more_results. Also check the disclaimers on the manual page for mysqli::store_result about how mysqli handles multiple result sets wherein one might not have data. You'll end up working with the mysqli_result class instead of mysqli_stmt.

木落 2024-10-29 04:58:52

因此,经过更多测试后,我发现这实际上并不是 MySQLi 库或我的代码中的错误。

解决方案?授予数据库用户对MySQL中数据库的“执行”权限。我以 root 身份(而不是脚本使用的实际用户)登录时编写并测试了 SQL 语句和函数。

哦,IT 的乐趣。

So, after more testing and what not, I find that it's not actually a bug in the MySQLi libraries or in my code.

The Solution? Give the database user the "Execute" permission for the database in MySQL. I wrote and tested the SQL statements and functions while I was logged in as root, not the actual user that the script was using.

Oh the joys of IT.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文