I have a field in a MySQL database called ‘location’ – it serves up North, South, East, West only.
I have used this code to get only the 4 results that are distinct:
$query_form = "SELECT DISTINCT location FROM hotel ORDER BY location ASC";
$result_form = mysqli_query($dbc, $query_form) or die('die query error');
$row_form = mysql_fetch_array($result_form, MYSQLI_NUM);
I wanted to use the four results from this query to populate a table such that:
<option value='1'>North</option>
<option value='2'>South</option>
<option value='3'>East</option>
<option value='4'>West</option>
I have used this:
foreach ($row_form['location'] as $k => $v) {
echo '<option value="' . $k . '">' . $v . '</option>\n';
}
but I fear that my approach will not work – with regret, I am a noob and unable to work out what is wrong!
Thanks
mysql_fetch_arraywill only (quoting the manual, emphasis mine) :So, you’ll have to call this function several times — actually, once per row (so, here, 4 times).
This is normally done with a loop, looping while you get results.
In your case, you’ll probably want to use something that looks like this :
Notes :
MYSQL_ASSOC, to get an associative array for each row : I think it’s easier to work this way.whileloop, you can use the$rowassociative array, indexed by column name.As a sidenote, when injecting data (such as strings) in some HTML code, you should escape the output properly, to avoid HTML injections.
See, for a solution, the
htmlspecialcharsfunction.