我正在尝试学习如何使用 HTML、PHP 和 MYSQL,并尝试使用这三种语言制作一个投票网站。我的 HTML 和 MYSQL 代码都很好并且可以工作,但我无法让我的 PHP 代码工作。我认为问题在于我使用的是单选按钮而不是候选人的文本输入,但我不知道如何转换数据。
HTML 代码:
<html>
<head>
<title>U.S Election 2016</title>
</head>
<body>
<h1>U.S Election 2016 - Voting Page</h1>
<form action="insert_vote.php" method="post">
<table border="0">
<tr>
<td>Voter ID</td>
<td><input type="text" name="VoterID" maxlength="13" size="13" /></td>
</tr>
<tr>
<td>Candidate :</td>
<td>
<input type="radio" name="Candidate" value="Hillary Clinton" checked>
Hillary Clinton<br>
<input type="radio" name="Candidate" value="Donald Trump" checked>
Donald Trump<br>
<input type="radio" name="Candidate" value="Gary Johnson" checked>
Gary Johnson<br>
<input type="radio" name="Candidate" value="Jill Stein" checked>
Jill Stein<br>
<input type="radio" name="Candidate" value="None" checked>
Undecided/None of the Above<br>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Cast Vote" /></td>
</tr>
</table>
</form>
</body>
</html>
PHP 代码:
<html>
<head>
<title>U.S Election 2016</title>
</head>
<body>
<h1>U.S Election 2016 - Voting Page</h1>
<?php
// create short variable names
$VoterID=$_POST['VoterID'];
$Candidate=$_POST['Candidate'];
if (!$VoterID || !$Candidate) {
echo "You have not entered all the required details.<br />"
."Please go back and try again.";
exit;
}
if (!get_magic_quotes_gpc()) {
$VoterID = intval($VoterID);
$Candidate = addslashes($Candidate);
}
@ $db = new mysqli('localhost', 'Voting2016', 'Voting123', 'voting');
if (mysqli_connect_errno()) {
Echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "insert into voters values
('".$VoterID."', '".$Candidate."')";
$result = $db->query($query);
if ($result) {
echo $db->affected_rows." Vote has been cast and stored into database.";
} else {
Echo "An error has occurred. Your vote was not added.";
}
$db->close();
?>
</body>
</html>
每次我提交表单时,它都会询问我是否要下载 PHP 文件:
最佳答案
您的 PHP 解释器似乎没有运行。如果它告诉您下载 PHP 文件,可能是因为没有任何东西可以解释它。查看 WAMP(Linux 上的 LAMP)以使其正确启动并运行。
编辑:看看代码,看来您是编程新手。我建议你看一些编程概念,比如MVC 。你需要将数据、逻辑和表示分开,否则就会很困惑,而困惑会产生错误。 PHP 允许你做一些令人讨厌的事情,在不太了解编程的情况下开始使用这种语言可能会给你带来一些坏习惯,所以要小心:)
关于PHP编码的烦恼,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40900865/