可以使用多个/嵌套的 MySQLi 语句吗?

Possible to use multiple/nested MySQLi statements?

提问人:Gilean 提问时间:9/22/2008 最后编辑:Manoj SharmaGilean 更新时间:4/13/2017 访问量:7879

问:

是否可以在前一个语句的调用范围内使用?如果没有,最好的解决方法是什么?MySQLi prepared statementfetch()

示例代码:

if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($item);
    while( $stmt->fetch() ) {
        /* Other code here */
        $itemSummary = $item + $magic;
        if($stmt2 = $link->prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) {
            $stmt2->bind_param("is", $itemID, $itemSummary);
            $stmt2->execute();
            $stmt2->close();
        }
    }
}
php mysql mysqli

评论


答:

2赞 Kibbee 9/22/2008 #1

您应该能够做到这一点,尽管您必须启动第二个连接。

2赞 peterbriers 11/5/2009 #2

或者使用store_result

17赞 Etherealone 8/12/2012 #3

这是单一的连接方式:

if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->store_result(); // <-- this
    $stmt->bind_result($item);
    while( $stmt->fetch() ) {
        /* Other code here */
        $itemSummary = $item + $magic;
        if($stmt2 = $link->prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) {
            $stmt2->bind_param("is", $itemID, $itemSummary);
            $stmt2->execute();
            $stmt2->store_result(); // <-- this
            /*DO WHATEVER WITH STMT2*/
            $stmt2->close();
        }
    }
}