How to implement MySQLi nested prepared statements

2019-03-05 02:30发布

I am trying to convert MySQL to MySQLi. And I cannot figure out why it brakes on

$stmt2->execute();

and returns error:

Call to a member function execute() on a non-object

Any issue or valid implementing of it!?

// SQL condition "WHERE group=''" where `group` is empty (NULL)
$result = "SELECT id, name FROM table WHERE group='' ORDER BY array ASC";

if ($stmt = $mysqli->prepare($result)) {
    $stmt->execute();
    $stmt->bind_result($id, $name);

    while ($stmt->fetch()) {
        // SQL condition "WHERE group='$id'" where $id defined in $stmt->bind_result($id, $name);
        $result2 = "SELECT name FROM table WHERE group='$id' ORDER BY array ASC";

        $stmt2 = $mysqli->prepare($result2);
        //$valid_stmt2 = $stmt2 === FALSE ? false : true;

        echo $name . "\n";

        //if ($valid_stmt2) {
            // Error cased on $stmt2->execute();
            $stmt2->execute();
            $stmt2->bind_result($name2);

            while ($stmt2->fetch()) {
                echo 'related to: ' . $name2 . "\n";
            }

            $stmt2->close();
        //}
    }

    $stmt->free_result();
    $stmt->close();
}

This question might be related to Possible to use multiple/nested MySQLi statements? Unfortunately I did not find it helpful since it does not provide a valid example or resource for issue.

Update: Simplified code example with comments.

1条回答
老娘就宠你
2楼-- · 2019-03-05 03:32

You first did

"SELECT id, url, name FROM links WHERE group='' ORDER BY array ASC"

Then you want to use the $id to do

"SELECT url, name FROM links WHERE group='$id' ORDER BY array ASC"

How would get result for that? If group equal empty string, then it will not equal $id(only if $id is empty string too but that's non sense.)

查看更多
登录 后发表回答