簡體   English   中英

在php mysqli准備好的語句中將數據附加到數組中

[英]Attach data in array in a php mysqli prepared statement

我想在這里寫一個簡單的函數。 這個想法是為了能夠調用該函數並顯示數據,但是我想知道是否有一種方法可以將其填充到某種類型的數組中,以便在調用函數時可以設置結果的樣式。 功能如下:

function getDBH() {
    static $DBH = null;
    if (is_null($DBH)) {
        $DBH = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    }
    return $DBH;
}
function selectInfo($limit, $offset){
    $DBH = getDBH();
    $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    $stmt->bind_result($id, $name, $email);
}

selectInfo()函數的此替換應返回一個多維數組,每個記錄包含一個關聯數組。 它並不依賴您事先知道語句中返回的字段,因為如果您以任何方式更改表,則select語句中的*可能會輕易破壞事情。

function selectInfo($limit, $offset) {
    $DBH = getDBH();
    $limit = (int) $limit;
    $offset= (int) $offset;
    $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    // get all field info in returned set
    $result_metadata = $stmt->result_metadata();
    $result_fields = $result_metadata->fetch_fields();  
    $result_metadata->free_result();
    unset($result_metadata);
    $bind_array = array();
    $current_row = array();
    $all_rows = array();
    foreach($result_fields as $val) {
        // use returned field names to populate associative array
        $bind_array[$val->name] = &$current_row[$val->name];
        }
    // bind results to associative array
    call_user_func_array(array($stmt, "bind_result"), $bind_array);
    // continually fetch all records into associative array and add it to final $all_rows array
    while($stmt->fetch()) $all_rows[] = $current_row;
    return $all_rows;
    }

編輯:改變了您的selectInfo()函數,因為我以前的答案太草率。 print_r(selectInfo(0,10)); 將打印出所有具有完整字段名稱的記錄。

$stmt->bind_result($id, $name, $email);

while (mysqli_stmt_fetch($stmt)) {
    $row = array('id' => $id, 'name' => $name, 'email' => $email);
    $rows[] = $row;
}

return $rows;

采用 ! 代替 ? 附加靜態數據。 附加帶引號的轉義數據。 是不安全的,但不是限制性的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM