我知道這是基本問題,但由於缺乏知識,我想知道如何將mysqli_result轉換爲數組和結果。Mysqli結果foreach結果集轉換爲數組
這裏是數據庫:
CREATE TABLE IF NOT EXISTS `slider` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
INSERT INTO `slider` (`id`, `title`) VALUES
(1, 'Slider 1'),
(2, 'Slider 2'),
(3, 'Slider 3'),
(4, 'Slider 4'),
(5, 'Slider 5'),
(6, 'Slider 6'),
(7, 'Slider 7'),
(8, 'Slider 8');
這裏是PHP文件:
$mysqli = new mysqli('host', 'user', 'pass', 'db',port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$query = "SELECT * FROM slider ORDER BY id";
if ($result = $mysqli->query($query)) {
echo "<pre>"; print_r($result); //This is mysqli_result Object
foreach($result as $row) { //Here is the magic how it is converted and row is retrieved
//echo "<pre>"; print_r($row);
printf ("<br>%s (%s)\n", $row["id"], $row["title"]);
}
while ($row = $result->fetch_assoc()) { //Normal way
//echo "<pre>"; print_r($row);
printf ("<br>%s (%s)\n", $row["id"], $row["title"]);
}
$result->free();
}
當我們穿越的同時,我們也必須使用fetch_ *方法來檢索結果,但是當我遍歷foreach,如何檢索結果? foreach循環如何隱式調用fetch_ *?
它是一個實現'Traversable'接口的類,所以使用'foreach()'自動提取。 – Barmar
有趣的知道,我會通過它。 – Kamal