从mysql_fetch_array查询创建表单 [英] Creating a form from mysql_fetch_array query
问题描述
我在MySQL数据库中有一个名为位置"的字段-它仅服务于北,南,东,西.
I have a field in a MySQL database called 'location' - it serves up North, South, East, West only.
我已使用此代码仅获得4个不同的结果:
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>
我用过这个:
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!
谢谢
推荐答案
mysql_fetch_array
仅(引用手册,重点是我的):
获取结果行作为 关联数组,数字数组或 两者
Fetch a result row as an associative array, a numeric array, or both
因此,您必须多次调用此函数-实际上,每行一次(因此,这里是4次).
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 :
$lineCounter = 1;
while ($row = mysql_fetch_array($result_form, MYSQL_ASSOC)) {
// Use your row, here.
// For instance : $row['location']
// And you can use the $lineCounter variable, to keep track of the current line number.
$lineCounter++;
}
注意:
- 我使用
MYSQL_ASSOC
来为每一行获取一个关联数组:我认为以这种方式工作更容易. - 在
while
循环的正文中,您可以使用$row
关联数组,并按列名索引.
- I used
MYSQL_ASSOC
, to get an associative array for each row : I think it's easier to work this way. - In the body of the
while
loop, you can use the$row
associative array, indexed by column name.
附带说明一下,以某些HTML代码注入数据(例如字符串)时,应正确地转义输出,以避免HTML注入.
As a sidenote, when injecting data (such as strings) in some HTML code, you should escape the output properly, to avoid HTML injections.
有关解决方案,请参见 htmlspecialchars
函数.
See, for a solution, the htmlspecialchars
function.
这篇关于从mysql_fetch_array查询创建表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!