Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to use multiple/nested MySQLi statements?

Tags:

php

mysql

mysqli

Is it possible to have a MySQLi prepared statement within the fetch() call of a previous statement? If not, what's the best way around it?

Example code:

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();
        }
    }
}
like image 917
Gilean Avatar asked Sep 22 '08 01:09

Gilean


3 Answers

This is the single connection way:

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();
        }
    }
}
like image 75
Etherealone Avatar answered Nov 15 '22 09:11

Etherealone


Or use store_result.

like image 34
peterbriers Avatar answered Nov 15 '22 09:11

peterbriers


You should be able to do that, although you make have to start a second connection.

like image 33
Kibbee Avatar answered Nov 15 '22 09:11

Kibbee