1 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
請(qǐng)耐心聽(tīng)我說(shuō),因?yàn)樽詮奈沂褂贸绦?mysqli 以來(lái)已經(jīng)很久了......
如果您希望動(dòng)態(tài)綁定列參數(shù)并執(zhí)行獲取循環(huán)(因?yàn)?mysqlnd 不是一個(gè)選項(xiàng)),那么這里的代碼可以實(shí)現(xiàn)這一點(diǎn)。
mysqli_stmt_execute($stmt);
// now before you loop on $stmt->fetch, you must bind all the columns that exist
// to a row which will hold the values during the looping on fetch (yes, confusing)
$row = array(); // will hold each fetch'd loop result
$params = array(); // something to pass keyed references to $row with
$params[] = $stmt; // add the $stmt object as first param (for procedural way)
$meta = mysqli_stmt_result_metadata($stmt);// get what those columns will be
while($field = $meta->fetch_field()) {
if (!isset($row[ $field->name ])) { $row[ $field->name ] = null; } // set if not set
$params[] = &$row[ $field->name ]; // add reference to keyed row value
}
$meta->close();// metadata no longer needed, close it
call_user_func_array('mysqli_stmt_bind_result', $params);
while (mysqli_stmt_fetch($stmt)) {
// in here you then have $row to use as before
echo $row['id'];
}
現(xiàn)在,你可能會(huì)認(rèn)為我在這里太過(guò)分了……是的。該示例用于處理未知的sql 列抓取(使用SELECT *語(yǔ)法)。但是,如果您知道所有列都出來(lái),則可以簡(jiǎn)單地在 while 循環(huán)之前綁定每一列,如下所示:
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $col2, $col3);
while (mysqli_stmt_fetch($stmt)) {
// in here you then use $id, $col2, $col3
echo $id;
}
這就是為什么切換到該P(yáng)DO庫(kù)可以使事情變得非常容易,因?yàn)樗峁┝嗽诤?jiǎn)單循環(huán)中簡(jiǎn)單地獲取具有關(guān)聯(lián)鍵名的行的規(guī)定,就像您所知道并喜歡的可用一樣mysqlnd。然而,如果PDO這也不是一個(gè)選項(xiàng),那么您將面臨痛苦且神秘的方法來(lái)處理“binds”和“mysqli”。
- 1 回答
- 0 關(guān)注
- 149 瀏覽
添加回答
舉報(bào)