使用 mySQL 查询填充 HTML 表单选择 [英] Populating a HTML form selection with a query of a mySQL

查看:46
本文介绍了使用 mySQL 查询填充 HTML 表单选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试运行一个 mySQL 查询,该查询填充一个 HTML 表单,在其中显示一个标记.我想从 mySQL 表中填充值和文本.这是我根据在不同网站上查找内容所尝试的方法,但没有成功

I have been trying to run a mySQL query that populates a HTML form where I present a tag. I would like to populate both the value and the text from the mySQL table. Here is what I tried based on finding things on different web sites, and it did not work

<select name="id">
   <?php

    require_once dirname(__FILE__) . '/db_connect.php';
    $db = new DB_CONNECT();

    $query="SELECT id, name FROM file order by name";
    $result=mysql_query($query) or die ("Query to get data from firsttable failed: " .mysql_error());

    while ($row = mysql_fetch_array($result)) {
    $id = $row[id];
    $name =$row[name];
      echo "<option value=\"$id\">
            $name
            </option>";
     }
   ?>
    </select>

评论:不起作用是指选择下拉列表为空.我确实从表单中取出 PHP 并将其放入它自己的 name.php 文件中以尝试运行它.它似乎工作.所以我在php中添加了echo语句来回显表单的开始和结束,以及初始选择行.这很好用,没有问题,下拉菜单填充得很好.回到上面的 HTML 表单,我确实在 PHP 中添加了一些其他的 echo 语句来输出一些调试语句.第一个回声总是被忽略,它不会添加任何选择项.其他回显行仅添加指定的文本,变量作为变量名输出,而不是内容.所以 $name 出现在选择下拉菜单中.

Comment: Did not work refers to the fact that the select drop down is empty. I did pull the PHP out of the form and put it in it's own name.php file to try and run it. it seemed to work. So I added echo statements in the php to echo out the start and end of the form, and the initial select line. This worked just great, no problems, the drop down was populated just fine. Back on the HTML form above, I did add a few other echo statements in the PHP to output some debug statements. The firs echo is always ignored, it does not add any select item. the other echo lines only adds the text specified, variables are output as the variable name, not the content. so $name shows up in the select drop down.

推荐答案

你需要在 id 和 name 周围加上单引号.那就是你需要替换这个

You need to put single quotes around id and name. That is you need to replace this

$id = $row[id];
$name =$row[name];

由此

$id = $row['id'];
$name =$row['name'];

不知道 DB_CONNECT 中的内容以及您的错误是什么,这是我对错误的最佳猜测.

without knowing what's in DB_CONNECT and what your error is this is my best guess at what's wrong.

这篇关于使用 mySQL 查询填充 HTML 表单选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆