Reputation: 67
I have a loop which displays the wanted rows but I also want each row to be stored in its own variable in php. I have a table that has an ID and an info column.
This displays the wanted ID and info:
if ($info = $stmnt2->fetch()) {
do {
echo "$info[id] . $info[info] </br> ";
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
I want each row to have its own variable so I can manipulate the data later down the line. Like the first row will be stored in a php variable called $one and the second row in $second. How can I do this?
Upvotes: 1
Views: 936
Reputation: 4028
$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);
Upvotes: 0
Reputation: 362
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>";
}
The array index will be same as the id in the DB. To Retrieve the content use
$array[1]['info'] //will retrieve content id id = 1
Upvotes: 0
Reputation: 43564
I wouldn't use a variable to solve this! Take an array instead:
$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!
//...
}
With the above example each item on rows
is one row ($rows[number_of_row - 1]
).
Hint:
$info[id]
and$info[info]
isn't valid. You have to replace these with$info['id']
and$info['info']
!
Upvotes: 3
Reputation: 1048
Just add $info
to an Array:
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
Upvotes: 1