2016-12-01 88 views
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文件的形式:

+0

爲什麼每個單選按鈕在輸入中都有「checked」? – Xorifelse

+1

對於你感覺到的問題是什麼,你能不能模糊一些?你是如何得出這是無線電輸入的?調試輸出在哪裏?試圖PDO /綁定參數,而不是誤導的SQL轉義呢?如何減少錯誤顯示抑制?這個特別的腳本也不晚了嗎? – mario

+0

你沒有提供太多的信息,但是如果我不得不猜測,你可能會遇到基於單選按鈕上的「name」屬性的問題。不要將它們命名爲「Candidate」,請嘗試「Candidate []」。另外,在PHP中,你應該做if(!empty($ VoterID)||!empty($ Candidate))。如果(!$ VoterID)只會在$ VoterID是布爾值的情況下正常工作。 – MMMTroy

回答

0

看起來你的PHP解釋器沒有運行。如果它告訴你下載一個PHP文件,可能是因爲沒有解釋它。看看WAMP(Linux上的LAMP)來正確啓動並運行它。

編輯:看看代碼,看起來你是編程新手。我建議你看看一些編程概念,如MVC。你需要分離數據,邏輯和表達,否則將是混亂,混亂造成錯誤。 PHP允許你做一些令人討厭的事情,並且從這種語言入手而不知道編程會給你帶來什麼壞習慣,所以請注意:)