two mysqli querys, one in a while loop

2019-06-11 21:07发布

问题:

Can't seam to find the answer to this. I have a mysqli loop statement. And in that loop I want to run another query. I cant write these two sql together. Is that possible? I thought since I use stmt and set that to prepare statement. So i add another variable stmt2. Running them seperate works, but run it like I wrote it gives me "mysqli Fatal error: Call to a member function bind_param() on a non-object"

Pseudocode :

loop_sql_Statement {
    loop_another_sql_statement(variable_from_firsT_select) {
       echo "$first_statement_variables    $second_statemenet_variables";
    }
}
                $sql = "select dyr_id, dyr_navn, type_navn, dyr_rase_id, dyr_fodt_aar, dyr_kommentar, dyr_opprettet, dyr_endret
                    from dyr_opphald, dyr, dyr_typer
                    where dyropphald_dyr_id = dyr_id
                    and dyr_type_id = type_id
                    and dyropphald_opphald_id = ?";

            $stmt = $mysqli->prepare($sql);
            $stmt->bind_param("i",
             $p_opphald_id);
            $stmt->execute(); 

            $stmt->bind_result($dyr_id, $dyr_navn, $type_navn, $dyr_rase_id, $dyr_fodt_aar, $dyr_kommentar, $dyr_opprettet, $dyr_endret);

            echo "<table>";
            while($stmt->fetch()) {
                echo "<tr><td>$dyr_navn</td><td>$type_navn</td><td>$dyr_rase_id</td><td>$dyr_fodt_aar</td><td>";

                $sql2 = "select ekstra_ledetekst, ekstradyr_ekstra_verdi from dyr_ekstrainfo, ekstrainfo where ekstradyr_ekstra_id = ekstra_id and ekstradyr_dyr_id = ?";
                try {

                    $stmt2 = $mysqli->prepare($sql2);
                    $stmt2->bind_param("i",
                     $dyr_id);
                    $stmt2->execute(); 

                    $stmt2->bind_result($ekstra_ledetekst, $ekstra_ledetekst);
                    echo "<td>";
                    while($stmt2->fetch()) {
                        echo "$ekstra_ledetekst => $ekstra_ledetekst<br>";
                    }
                }catch (Exception $e) {}
                echo "</td></tr>";
            }
            echo "</table>";

The answer:

Silly me, I didnt know I had to have two mysqli connection. So the solution was to declare another mysqli connection.

$mysqli = new mysqli($start, $name, $pwd, $selected_db);
$mysqli2 = new mysqli($start, $name, $pwd, $selected_db);

回答1:

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