准备好的声明不工作

Prepared Statement Not working

如果有一段代码对我来说很难解决。我不知道如何才能找到比这更多的错误。

                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("/(.*)\/(.*)\/(.*)\//", "//", $this->_pathLus); // part of Loop and works
            }

我为找到解决方案所做的工作:

结果:

注意: <data>, <data2>, <data3> 是这个例子的替代品

提前致谢

编辑:更正

编辑:

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

但是如何得到发生的错误?

我是怎么发现问题的:

我把echo $stmtToegang->error . 3;改成了echo $db->error . 3; 这样我发现了以下错误:

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

我在哪里找到了解决方案: Answer here on SO

问题在于此 stmt 查询(select 类型)是另一个 stmt 查询(select 类型)的一部分,因为:

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

所以我调试嵌套准备语句(select类型)的代码如下:

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 

希望对大家有所帮助