简体   繁体   中英

MySQLi Prepared Statement not working in WHILE Loop

Hi there,

I'm working on a query inside a While loop. However, the Second run is not working. (The While is ended later, after some results get echoed). I've tried calling the second query $stma , however this resulted in the same error.

Error

Fatal error: Call to a member function bind_param() on a non-object in PATH on line 96

Code

 // Prepare Query
    $stmt = $db->prepare("SELECT id, fullname, shortname FROM languages WHERE (state = '0')");
    $stmt->execute();

    // Get result from query.
    $stmt->bind_result($lang_id, $lang_name, $lang_short);

    // While Loop
    while($language = $stmt->fetch()){

        // Get Language Texts
        $stmt = $db->prepare("SELECT id, article_id, article_language, article_text, article_recuse, article_spec FROM article_content WHERE article_id = ? AND article_language = ?");

        $stmt->bind_param("is", $artikel_nummer, $lang_short); // This is line 96.
        $stmt->execute();

        // Get result from query.
        $stmt->bind_result($t_id, $t_articleid, $t_language, $t_text, $t_recuse, $t_spec);
        $stmt->fetch();

I'm fairly new to prepared statements, so I'm not sure what exactly the problem is. I've ran a var_dump() on the query and it returned false, however, running the query elsewhere or outside the WHILE loop is working (When I Define the two variables by hand).

I've echoed $artikel_nummer and $lang_short , and it returns their values.

The question is the following: Why is the second query not running, and thus returning the error as stated above?

In your loop, you are overriding your $stm variable which holds a reference to your initial prepared statement (and indeed is the condition of your loop). For all queries happening inside loop, you must choose a different variable name:

while($language = $stmt->fetch()){

        // Get Language Texts
        $_stmt = $db->prepare("SELECT id, article_id, article_language, article_text, article_recuse, article_spec FROM article_content WHERE article_id = ? AND article_language = ?");

        $_stmt->bind_param("is", $artikel_nummer, $lang_short); // This is line 96.
        $_stmt->execute();

        // Get result from query.
        $_stmt->bind_result($t_id, $t_articleid, $t_language, $t_text, $t_recuse, $t_spec);
        $_stmt->fetch();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM