2016-12-01 87 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允许你做一些令人讨厌的事情,并且从这种语言入手而不知道编程会给你带来什么坏习惯,所以请注意:)