我正在阅读关于 PHP 和 HTML 的教程,教程中使用的代码对我来说并不像它演示的那样工作,我想了解原因。我在http://jsfiddle.net/csmart/vkPJf/上设置了一个 jsfiddle,这样你就可以看到发生了什么。该代码应该与数据库连接并添加和打印表格数据。代码似乎到达了打印名为 Courses 的表的部分,但它失败了。连接数据库似乎不是失败,因为我可以注释掉失败的代码并使用插入语句在表中创建新的数据行。html嵌入php的方式是否有问题,应该如何更正代码?谢谢。
<!DOCTYPE html><html><head>
<script src="jquery.min.js"></script>
<script src="jquery.validate.js"></script>
<script>
$(document).ready(function() {$("form").validate();});
</script>
</head><body>
<form method="post">
cid: <input name="cid" class="required digits" maxlength="3" minlength="3"><BR>
title: <input name="title" class="required" maxlength="200"><BR>
prof: <input name="prof" maxlength="64"><BR>
cred: <input name="cred" class="required digits" maxlength="1" minlength="1"><BR>
cap: <input name="cap" class="required digits" maxlength="2" minlength="2"><BR>
<input type="submit" value="OK">
</form>
<?php
ini_set('display_errors', 'On');
$dbhost = 'XXXXXXXX';
$dbname = 'XXXXXXXX';
$dbuser = 'XXXXXXXX';
$dbpass = 'XXXXXXXX';
$mysql_handle = mysql_connect("$dbhost", "$dbname", "$dbpass", "$dbuser")
or die("Error connecting to database server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname ");
$cid = array_key_exists("cid", $_REQUEST) ? $_REQUEST["cid"] : 0;
$title = array_key_exists("title", $_REQUEST) ? $_REQUEST["title"] : '';
$prof = array_key_exists("prof", $_REQUEST) ? $_REQUEST["prof"] : '';
$cred = array_key_exists("cred", $_REQUEST) ? $_REQUEST["cred"] : 0;
$cap = array_key_exists("cap", $_REQUEST) ? $_REQUEST["cap"] : 0;
if($cid <= 0) echo"";
else if (!preg_match('/^[0-9]{3}$/',$cid)) echo "Invalid cid";
else if (!preg_match('/^[0-9]{3}$/',$cred)) echo "Invalid cred";
else if (!preg_match('/^[0-9]{3}$/',$cap)) echo "Invalid cap";
else if($cid < 0) {
$rs = mysql_query("select cid from courses where cid = ".$cid);
if (mysql_numrows($rs) == 0) {
mysql_query("insert into courses(cid,cap,cred,title,prof) values("
. $cid . "," . $cap . "," . $cred
. ",'" . mysql_real_escape_string($title) . "'"
. ",'" . mysql_real_escape_string($prof) . "')"
);
}
else {
mysql_query("update courses set cap=".$cap.", cred=".$cred . ", title='". mysql_real_escape_string($title) . "'" . ", prof='". mysql_real_escape_string($prof) . "'" . " where cid=".$cid
};
}
}
$rs = mysql_query("select cid,prof,cred,cap,title from courses");
$nrows=mysql_numrows($rs);
echo "Courses<table>";
for ($i = 0; $i < $nrows; $i++) {
echo "<tr>";
echo "<td>".htmlspecialchars(mysql_result($rs,$i,"cid"))."</td>";
echo "<td>".htmlspecialchars(mysql_result($rs,$i,"title"))."</td>";
echo "<td>".htmlspecialchars(mysql_result($rs,$i,"prof"))."</td>";
echo "<td>".htmlspecialchars(mysql_result($rs,$i,"cred"))."</td>";
echo "<td>".htmlspecialchars(mysql_result($rs,$i,"cap"))."</td>";
echo "</tr>";
}
echo '</table>';
mysql_close($mysql_handle);
?>
</body></html>