I'm currently new to php and learning but after doing a bit of test, I know that while
can't be used twice but I'm not sure how to exactly reset it.
I see that in some scenarios people use reset($variable)
but that doesn't seem to work in my case.
In case if it matters, I'm trying to use mysqli
to retrieve back my dropdown menu as a selection, the first one works, but the second one doesn't works at all.
<?php
echo '<select>';
while(list($stateID, $stateName) = $result->fetch_row())
{
echo '<option value="$stateName">';
echo "$stateName";
echo '</option>';
}
echo '</select>';
?>
<br>
<br>
To:
<?php
echo '<select>';
while(list($stateID, $stateName) = $result2->fetch_row())
{
echo '<option value="$stateName">';
echo "$stateName";
echo '</option>';
}
echo '</select>';
?>
additionally, in case if it's needed, here's my results on searching in mysql.
<?php
include 'connect.php';
$query = "SELECT * FROM LOCATION";
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
$result2 = $mysqli->query($query, MYSQLI_STORE_RESULT);
if(!$result) {
echo($mysqli->error);
exit();
}
?>
While this method works where I created 2 variables with results 1 and 2, but I have a feeling this isn't the right way to go, especially in the event if I need to reuse the same code over and over again.
What you're doing in those while
statements is stepping over the list of rows you got from the database. It's true that you can't iterate over the list twice*, so you can try something different: iterate over the list once, and save the results so you can reuse it. For example:
Do this after you query the database:
$data = [];
while(list($stateID, $stateName) = $result->fetch_row())
{
$data[] = [ 'stateID' => $stateID, 'stateName' => $stateName ];
}
All I've done here is iterated over the list of rows and saved the data into a variable. Now you can use the variable instead of trying to access the MySQL results:
echo '<select>';
foreach ($data as $d) {
echo '<option value="'.$d['stateName'].'">";
echo $d['stateName'];
echo '</option>';
}
And because the data is stored in an array you can use it as many times as you like.
* It may be possible to reset the pointer on the MySQL result set, but my approach is simpler and (probably) performs a little better, since you've copied the data you want into a plain old PHP array