user4431269
user4431269

Reputation:

Prepared Statement Not working

if have a piece of code that is to hard for me to solve.. And i don't know how i can find the error more than this.

                while($this->_pathLus != $this->hoofdMap) { //loop works fine, tested and confirmd
                echo $this->_pathLus . 0; //$this->_pathLus = <data4>
                if ($stmtToegang = $db->prepare("SELECT <data>, <data2> FROM `<data3>` WHERE <data> = ? LIMIT 5")) {
                    $stmtToegang->bind_param("s",$this->_pathLus);

                    $stmtToegang->execute();

                    $stmtToegang->bind_result($<data>, $<data2>);

                    while ($stmtToegang->fetch()) {
                        echo $<data> . 1;

                        echo $stmtToegang->error . 2;

                    }
                } else { //to be sure if-stmt-prep is FALSE
                    echo $stmtToegang->error . 3;
                }
                $this->_pathLus = preg_replace("/(.*)\/(.*)\/(.*)\//", "$1/$2/", $this->_pathLus); // part of Loop and works
            }

What i did to find solution:

Results:

Note: <data>, <data2>, <data3> are replacements for this example

Thanks in advance

Edit: Correction

Edit:

mysqli_prepare() returns a statement object or FALSE if an error occurred.

But how get the error that Happens ?

Upvotes: 2

Views: 219

Answers (1)

user4431269
user4431269

Reputation:

How i did find the problem:

i altered echo $stmtToegang->error . 3; into echo $db->error . 3; This way i found the following error:

Commands out of sync; you can't run this command now

Where i found a solution: Answer here on SO

Problems was that this stmt-query (select type) was a part of another stmt-query (select type) because:

mysqli uses unbuffered queries by default (for prepared statements;)

So my code to debug a nested prepared statement (select-type) is as followed :

if($stmt = $mysqli->prepare($sql)) {
    <$stmt->bind_param()->execute()->bind_result() code>

    $stmt->store_result(); // store them !important

    while ($stmt->fetch()) {
        //code

        if($stmt2 = $mysqli->prepare($sql)) {
            <$stmt2->bind_param()->execute()->bind_result() code>

            $stmt2->store_result(); // store them !important

            while ($stmt2->fetch()) {
                //code
            }
            $stmt2->free_result(); // free them
            $stmt2->close(); // close them

            echo $stmt2->error; // report error
        }  else {
            echo $mysqli->error; // report error
        }
    }
    $stmt->free_result(); // free them
    $stmt->close(); // close them

    echo $stmt->error; // report error
} else {
    echo $mysqli->error; // report error
}

//edit: <$stmt->bind_param()->execute()->bind_result() code> for an better view 

Hope it can help somone

Upvotes: 1

Related Questions