0
我在學習如何使用HTML,PHP和MYSQL並嘗試使用這三種語言的投票網站。我的HTML和MYSQL代碼都很好,並且工作正常,但我無法讓我的PHP代碼正常工作。我相信問題是我使用單選按鈕而不是候選人的文本輸入,但我不知道如何轉換數據。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文件的形式:
爲什麼每個單選按鈕在輸入中都有「checked」? – Xorifelse
對於你感覺到的問題是什麼,你能不能模糊一些?你是如何得出這是無線電輸入的?調試輸出在哪裏?試圖PDO /綁定參數,而不是誤導的SQL轉義呢?如何減少錯誤顯示抑制?這個特別的腳本也不晚了嗎? – mario
你沒有提供太多的信息,但是如果我不得不猜測,你可能會遇到基於單選按鈕上的「name」屬性的問題。不要將它們命名爲「Candidate」,請嘗試「Candidate []」。另外,在PHP中,你應該做if(!empty($ VoterID)||!empty($ Candidate))。如果(!$ VoterID)只會在$ VoterID是布爾值的情況下正常工作。 – MMMTroy