PHP mysqli - 如何将我的代码转换为准备好的语句代码

时间:2018-02-03 21:59:38

标签: php mysqli prepared-statement

我已经尝试了一系列不同的例子,说明如何做好准备好的陈述,但它对我没用。

我将此代码转换为预准备语句代码时遇到问题

Margin

我试过这个,但它没有用

function get_all_crew() {

            global $db;

            $query = "SELECT * FROM crew WHERE crew_active_state = 1";

            if ($result = $db->query($query)) {
                if ($result->num_rows) {
                   while ($row = $result->fetch_object()) {
                       $posts[] = $row;
                   }
                   $result->free(); // Frigør hukommlsen

                   return $posts;
                }
            }
        } 

1 个答案:

答案 0 :(得分:0)

我总是这样做而且有效。我从不使用fetch_object(),但您只是要求转换为参数化语句,所以在这里:

<?php
function get_all_crew(){
    try {
        global $db;
        $query = "SELECT * FROM `crew` WHERE `crew_active_state`=?";
        if($stmt = $db->prepare($query)){
            $crew_active_state = 1;
            $stmt->bind_param('i', $crew_active_state); // OR $stmt->bind_param('i', 1);
            $stmt->execute();
            $result = $stmt->get_result();
        }
        if($db->errno){
            throw new Exception('MySQL error: '.$db->error); // if there is an error, the rest of the code won't be executed.
        }
        while($rows = $result->fetch_object()) {
            $posts[] = $rows;
        }
        unset($stmt);
        return $posts;
    } catch(Exception $e){
        return ['error' => $e->getMessage()]; // just for the sake of returning an array as well.
    }
}
?>