如何实现MySQLi嵌套预处理语句?

时间:2012-06-15 01:30:19

标签: php mysql mysqli mysqli-multi-query

我正在尝试将MySQL转换为MySQLi。我无法弄清楚为什么它会刹车

$stmt2->execute();

并返回错误:

  

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

任何问题或有效实施!?

// 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();
}

这个问题可能与Possible to use multiple/nested MySQLi statements?有关。遗憾的是我没有发现它有用,因为它没有提供有效的问题示例或资源。

更新:带注释的简化代码示例。

1 个答案:

答案 0 :(得分:0)

你第一次

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

然后你想使用$id来做

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

如何获得结果呢?如果group等于空字符串,那么它将不等于$id(仅当$id为空字符串时才有效,但这是无意义的。)