Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function split() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 101

Deprecated: Function eregi_replace() is deprecated in /home3/vvaswani/sql.php on line 301

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home3/vvaswani/public_html/community/columns/trog/article.php on line 107

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home3/vvaswani/public_html/community/columns/trog/article.php on line 109

Deprecated: Function ereg_replace() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 124

Deprecated: Function ereg_replace() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 125

Deprecated: Function split() is deprecated in /home3/vvaswani/public_html/community/columns/trog/article.php on line 127

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174

Deprecated: Function ereg() is deprecated in /home3/vvaswani/db-mysql.php on line 174
The Melonfire Community - Trog
Logo         Community
  Trog
Services
The Company
Community
Columns
Your Account
Contact Us
 
 
PHP 101 (part 14): Going to the Polls
Create an online voting system with PHP and MySQL

| Rocking The Vote |

With the database taken care of, it's time to put together the web pages that the user sees. The first of these is user.php, which connects to the database to get the latest poll question and displays it together with all its possible responses. Take a look:


<html>
<head><basefont face = 'Arial'></head>
<body>

<?php
// include configuration file
include('config.php');

// open database connection
$connection = mysql_connect($host, $user, $pass) or die('ERROR: Unable to connect!');

// select database
mysql_select_db($db) or die('ERROR: Unable to select database!');

// generate and execute query
$query = "SELECT qid, qtitle FROM questions ORDER BY qdate DESC LIMIT 0, 1";
$result = mysql_query($query) or die("ERROR: $query.".mysql_error());

// if records are present
if (mysql_num_rows($result) > 0) {
    $row = mysql_fetch_object($result);

    // get question ID and title
    $qid = $row->qid;
    echo '<h2>'.$row->qtitle .'</h2>';
    echo "<form method = post action = 'user_submit.php'>";
   
    // get possible answers using question ID
    $query = "SELECT aid, atitle FROM answers WHERE qid = '$qid'";
    $result = mysql_query($query) or die("ERROR: $query.".mysql_error());

    if (mysql_num_rows($result) > 0) {

        // print answer list as radio buttons
        while ($row = mysql_fetch_object($result)) {
            echo "<input type = radio name = aid value = '".$row->aid."'>'".$row->atitle."'</input><br />";
        }

    echo "<input type = hidden name = qid value = '".$qid."'>";
    echo "<input type = submit name = submit value = 'Vote!'>";
    }
   
    echo '</form>';
}

// if no records present, display message
else {
    echo '<font size="-1">No questions currently configured</font>';
}

// close connection
mysql_close($connection);
?>

</body>
</html>


Pay special attention to the SQL query I'm running: I'm using the ORDER BY, DESC and LIMIT keywords to ensure that I get the latest record (question) from the questions table. Once the query returns a result, the record ID is used to get the corresponding answer list from the answers table. A while() loop is then used to print the answers as a series of radio buttons. The record ID corresponding to each answer is attached to its radio button; when the form is submitted, this identifier will be used to ensure that the correct counter is updated.

Note that if the database is empty, an error message is displayed. In this example, we've already inserted one question into the database, so you won't see it at all; however, it's good programming practice to ensure that all eventualities are accounted for, even the ones that don't occur that very often.

The file config.php included at the top of the script contains the access parameters for the MySQL database. This data has been placed in a separate file to make it easy to change it if you move the application to a new server. Take a look inside:


<?php
// database access parameters
$host = 'localhost';
$user = 'guest';
$pass = 'guessme';
$db = 'db3';
?>


Here's what the form looks like:

Output image

Okay, now you've got the poll displayed. Users are lining up to participate, and clicks are being generated by the millions. What do you do with them?

The answer lies in the script that gets activated when a user casts a vote and submits the form described earlier. This script, user_submit.php, takes care of updating the vote counter for the appropriate question/answer combination. Take a look:


<html>
<head><basefont face = 'Arial'></head>
<body>

<?php
if (isset($_POST['submit'])) {

    if (!isset($_POST['aid'])) {
        die('ERROR: Please select one of the available choices');
    }

    // include configuration file
    include('config.php');
   
    // open database connection
    $connection = mysql_connect($host, $user, $pass) or die('ERROR: Unable to connect!');
   
    // select database
    mysql_select_db($db) or die('ERROR: Unable to select database!');
   
    // update vote counter
    $aid = mysql_escape_string($_POST['aid']);
    $qid = mysql_escape_string($_POST['qid']);
    $query = "UPDATE answers SET acount = acount + 1 WHERE aid = ".$aid." AND qid = ".$qid;
    $result = mysql_query($query) or die("ERROR: $query. ".mysql_error());

    // close connection
    mysql_close($connection);


    // print success message   
    echo 'Your vote was successfully registered!';
}
else {
    die('ERROR: Data not correctly submitted');
}
?>

</body>
</html>


This script first checks to ensure that an answer has been selected, by verifying the presence of the answer ID $_POST['aid']. Assuming the ID is present, the script updates the database to reflect the new vote and displays an appropriate message.

Now, flip back through your notebook and look at the initial requirement list. Yup, you can cross off Item #1. Onwards to Item #2...


How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system.

Read more, or grab your copy now!


previous page more like this  print this article  next page
 
Search...
 
In trog...
Logging With PHP
Building A Quick-And-Dirty PHP/MySQL Publishing System
Output Buffering With PHP
Date/Time Processing With PHP
Creating Web Calendars With The PEAR Calendar Class
more...
 
In the hitg report...
Crime Scenes
Animal Attraction
Lord Of The Strings
more...
 
In boombox...
Patience - George Michael
Think Tank - Blur
My Private Nation - Train
more...
 
In colophon...
Hostage - Robert Crais
The Dead Heart - Douglas Kennedy
Right As Rain - George Pelecanos
more...
 
In cut!...
American Chai
The Core
Possession
more...
 
Find out how you can use this article on your own Web site!


Copyright © 1998-
Strict Standards: mktime(): You should be using the time() function instead in /home3/vvaswani/public_html/community/columns/trog/article.php on line 731
2018 Melonfire. All rights reserved
Terms and Conditions | Feedback