[英]store rows retrieved from database as separate variables in php
我有一個循環,顯示所需的行,但我也希望將每一行存儲在php中自己的變量中。 我有一個具有ID和信息列的表。
這將顯示所需的ID和信息:
if ($info = $stmnt2->fetch()) {
do {
echo "$info[id] . $info[info] </br> ";
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
我希望每一行都有自己的變量,以便稍后可以處理數據。 就像第一行將存儲在名為$ one的php變量中,第二行存儲在$ second中。 我怎樣才能做到這一點?
我不會使用變量來解決這個問題! 取一個數組代替:
$rows = [];
if ($info = $stmnt2->fetch()) {
do {
$rows[] = $info;
echo $info['id'].$info['info']."</br>";
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
if (!empty($rows)) {
//you can change the values of the rows like the following.
$rows[0]['id'] = 1; // The ID of the first row!
$rows[0]['info'] = 'Some Info'; // The info of the first row!
$rows[1]['id'] = 2; // The ID of the second row!
$rows[1]['info'] = 'Some Info'; // The info of the second row!
//...
}
在上面的示例中, rows
上的每個項目都是一行( $rows[number_of_row - 1]
)。
提示:
$info[id]
和$info[info]
無效。 您必須用$info['id']
和$info['info']
替換它們!
只需將$info
添加到數組:
if ($info = $stmnt->fetch()) {
$array = [];
do {
echo "$info[id] . $info[info] </br> ";
$array[] = $info;
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
// Do stuff with all rows
$mysqli = new mysqli('localhost','root','','yourdb');
if($resultobj=$mysqli->query("select * from yourtable limit 4")){
list($one,$two,$three,$four)=$resultobj->fetch_all();
}
print_r($one);
if ($info = $stmnt2->fetch()) {
$array=[];
do {
$array[$info['id']][]=$info; //the array index will be the same as id from the db
echo "$info[id] . $info[info] </br> ";
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
數組索引將與數據庫中的ID相同。 檢索內容使用
$array[1]['info'] //will retrieve content id id = 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.