I am using PHP to create a voting system and I have a form that I am inserting into MySQL database. I am going to use JavaScript to ensure that the user selects at least one candidate but not more than three, but I want to validate on the server side as well. Here is the web form for the page:
<form method="post" action="post.php">
<input type="checkbox" name="vote[FR01]" value="ON"> Freshman Candidate 1 <br />
<input type="checkbox" name="vote[FR02]" value="ON"> Freshman Candidate 2 <br />
<input type="checkbox" name="vote[FR03]" value="ON"> Freshman Candidate 3 <br />
<input type="checkbox" name="vote[FR04]" value="ON"> Freshman Candidate 4 <br />
<input type="checkbox" name="vote[FR05]" value="ON"> Freshman Candidate 5 <br />
<input type="checkbox" name="vote[FR06]" value="ON"> Freshman Candidate 6 <br />
<input type="submit" name="submit" value="submit">
</form>
I know I will need to use a for loop however, could anyone explain how I could use those array key indexes which are the column names in the database?
How about this?
if (isset($_POST['submit'])) {
$checkedCandidates = 0;
$values = $_POST['vote'];
$checkedCandidates = count($values);
if ($checkedCandidates < 1) {
echo 'You need to check at least one candidate.';
} elseif ($checkedCandidates >= 4) {
echo 'You can only check up to three candidates.';
} else {
echo 'Checked candidates: ' . var_dump($values);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.