0

我有问题。我需要制作动态 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>
4

2 回答 2

2

正如@Michael Berkowski 在评论中所建议的那样,protokoly和之间目前没有空格ORDER 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 语句的双引号字符串中将数组引用括在括号中,以简化它并消除多重连接。

于 2012-10-29T17:38:20.363 回答
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>
于 2012-10-29T23:10:47.730 回答