从MYSQL DB填充的动态SELECT TAG

时间:2012-10-29 17:32:36

标签: php html mysql

我有问题。我需要制作动态SELECT标签,其中OPTIONS是从mySQL DB动态填充的。我有这个代码,但它不起作用。因此,如果你有一些纠正或想法如何以其他方式,我会非常感谢:)非常感谢!

<SELECT>
<?php
 $con = mysql_connect("localhost", "root", "123456");
mysql_select_db("aplikace",$con);
$result = ("SELECT * kod FROM protokoly".
"ORDER BY kod");
$rs = mysql_query($result);
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++) {
    $r = mysql_fetch_array($rs);
    echo "<OPTION VALUE=\"".$r["kod"]."\">".$r["kod"]."</OPTION>";
}
?>
</SELECT>

2 个答案:

答案 0 :(得分:2)

正如@Michael Berkowski在评论中所说,protokolyORDER BY之间目前没有空格。这将导致MySQL错误,但您没有看到导致难以进行故障排除的错误。

如果出现错误,您可以修改代码以输出错误,如下所示:

$rs = mysql_query($result) or die('Error during query: ' . mysql_error());

如果mysql_query()失败,die()调用mysql_error()将输出最新MySQL错误的内容,帮助您解决问题。

修改

为了说明die()的使用情况,我编辑了您的代码,如下所示:

<?php
// Place at top of file
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>

<SELECT>
<?php
$con = mysql_connect("localhost", "root", "123456") or die('Connection failed: ' . mysql_error());
mysql_select_db("aplikace", $con) or die('Cannot select database: ' . mysql_error());
$result = ("SELECT * kod FROM protokoly ORDER BY kod");
$rs = mysql_query($result) or die('Query failed: ' . mysql_error());
$nr = mysql_num_rows($rs) or die('Failed to get num_rows: ' . mysql_error());
for ($i = 0; $i < $nr; $i++)
{
    $r = mysql_fetch_array($rs);
    echo "<OPTION VALUE=\"{$r['kod']}\">{$r['kod']}</OPTION>";
}
?>
</SELECT>

请注意,使用mysql_...()函数的语句包括mysql_error()内的die(),以便输出任何MySQL错误。我还在echo语句的双引号字符串中用括号括起数组引用,以简化它并消除多个连接。

答案 1 :(得分:0)

<SELECT>
<?php

//added error checking.
if (!($con = mysql_connect("localhost", "root", "123456")))
{
    die("Could not connect to database server. " . mysql_errno() . " => " . mysql_error());
}

//added error checking.
if (!mysql_select_db("aplikace",$con))
{
    die("Could not select database. " . mysql_errno() . " => " . mysql_error());
}

//removed *, pushed ORDER BY onto same line
$sql = "SELECT kod FROM protokoly ORDER BY kod";

//added error checking. added connection parameter
if (!($rs = mysql_query($sql,$con)))
{
    die("Could not execute query. " . mysql_errno() . " => " . mysql_error());
}

//added condition
if (($nr = mysql_num_rows($rs)) == 0)
{
    die("No options to give!");
}

//changed to while loop that checks result of function return
while ($r = mysql_fetch_array($rs))
{
    //changed " to ' to get rid of \"
    echo '<OPTION VALUE="' . $r["kod"] . '">' . $r["kod"] . '</OPTION>';
}
?>
</SELECT>