Design and Implementation of the PHP + MySQL Voting System

Source: Internet
Author: User
Tags preg

The system is not big. I took three steps to complete the system.
• Database Design
• System Framework Design
• Front-end beautification

Database Design
Three tables are designed: the voting result statistical table (count_voting), the voter record table (ip_votes), and the user table (user)
The voting result statistical table is used to count the final voting records. I have set four fields for it: the name of the voting item (SelectName) and the LabelName of the voting item (LabelName) number of votes (CountVotes ).

The voter record table is used to register the ip address, Location, VoteTime, and SelectName of the voter ). Then I add an ID to it.

The User table is mainly used by the Administrator, including the user name and password (passwd ).

The SQL script for table generation is as follows:Copy codeThe Code is as follows :--
-- Table structure 'count _ voting'
--
Drop table if exists 'count _ voting ';
Create table if not exists 'count _ voting '(
'Selectname' varchar (40) not null,
'Labelname' varchar (40) not null,
'Countvotes 'bigint (20) unsigned not null,
Unique key 'selectname' ('selectname '),
KEY 'countvotes '('countvotes '),
KEY 'countvotes _ 2' ('countvotes '),
KEY 'countvotes _ 3' ('countvotes ')
) ENGINE = InnoDB default charset = utf8 COMMENT = 'vote statistics ';
----------------------------------------------------------
--
-- Table structure 'IP _ votes'
--
Drop table if exists 'IP _ votes ';
Create table if not exists 'IP _ votes '(
'Id' bigint (20) unsigned not null auto_increment COMMENT 'voter number: auto incrementing ',
'IP' varchar (15) not null comment 'voter ip ',
'Location' varchar (40) not null comment' voter Location ',
'Votetime' datetime not null,
'Selectname' varchar (40) not null,
Primary key ('id '),
KEY 'id' ('id '),
KEY 'selectname' ('selectname ')
) ENGINE = InnoDB default charset = utf8 AUTO_INCREMENT = 4;
--
-- Trigger 'IP _ votes'
--
Drop trigger if exists 'vote _ count_after_insert_tr ';
DELIMITER //
Create trigger 'vote _ count_after_insert_tr 'after insert on 'IP _ votes'
For each row update count_voting SET CountVotes = CountVotes + 1 WHERE SelectName = NEW. SelectName
//
DELIMITER;
----------------------------------------------------------
--
-- Table structure 'user'
--
Drop table if exists 'user ';
Create table if not exists 'user '(
'Name' varchar (10) not null comment 'administrator username ',
'Passwd' char (32) not null comment' logon password MD5 value'
) ENGINE = InnoDB default charset = utf8 COMMENT = 'user table ';
--
-- Store the data in the table 'user'
--
Insert into 'user' ('name', 'passwd') VALUES
('Ttxi', '700469ca1555900b18c641bf7b0a1fa1 '),
('Jitttanwa ', 'adac5659956d68bcbc6f40aa5cd00d5c ');
--
-- Restrict exported tables
--
--
-- Restrict table 'IP _ votes'
--
Alter table 'IP _ votes'
Add constraint 'IP _ votes_ibfk_1 'foreign key ('selectname') REFERENCES 'count _ voting' ('selectname') on delete cascade on update cascade;

From the script, we can see that I have created a trigger. when inserting data into the ip_votes table, I will add 1 TO THE CountVotes FIELD IN THE count_voting table. The last sentence is to set the external Association word.
Framework Design
OperatorDB class is used to operate databases, and OperatorVotingDB class is used to operate specific sets of the system.
To use PDO to operate databases, we can encapsulate the following:Copy codeThe Code is as follows :/**
* Database operations
* Encapsulate PDO for convenient operations
*/
Class OperatorDB
{
// Basic information for connecting to the database
Private $ dbms = 'mysql'; // database type. for developers, you only need to change this type to use different databases.
Private $ host = 'localhost'; // Database host Name
Private $ dbName = 'voting '; // database used
Private $ user = 'voting'; // database connection username
Private $ passwd = 'voting '; // Password
Private $ pdo = null;
Public function _ construct ()
{
// Dl ("php_pdo.dll ");
// Dl ("php_pdo_mysql.dll ");
$ This-> dsn = "$ this-> dbms: host = $ this-> host; dbname = $ this-> dbName ";
Try
{
$ This-> conn = new PDO ($ this-> dsn, $ this-> user, $ this-> passwd); // initialize a PDO object, is to create a database connection object $ db
}
Catch (PDOException $ e)
{
Die ("<br/> database connection failed (creater PDO Error !) : ". $ E-> getMessage ()." <br/> ");
}
}
Public function _ destruct ()
{
$ This-> pdo = null;
}
Public function exec ($ SQL)
{
}
Public function query ($ SQL)
{
}
}

Encapsulate the information of the connected database to facilitate subsequent operations.Copy codeThe Code is as follows: <? Php
Require_once 'operatordb. php ';
Class OperatorVotingDB
{
Private $ odb;
Public function _ construct ()
{
$ This-> odb = new OperatorDB ();
}
Public function _ destruct ()
{
$ This-> odb = null;
}
/**
* Clear all tables in the Voting data
*
* Call the database operation class to perform clear database operations
*/
Public function clearTables ()
{
$ Sqls = array ("TRUNCATE ip_votes;", "TRUNCATE count_voting ;");
$ This-> odb-> exec ($ sqls [0]);
$ This-> odb-> exec ($ sqls [1]);
}
/**
* Reset the CountValues field in the count_voting table to 0.
*
*/
Public function resetCountValues ()
{
$ SQL = "UPDATE count_voting SET CountVotes = 0 ;";
$ This-> odb-> exec ($ SQL );
}
/**
* Vote
* Write information to the ip_votes table
* @ Param type $ ip
* @ Param type $ loc
* @ Param type $ time
* @ Param type $ name
*/
Public function vote ($ ip, $ loc, $ name)
{
$ SQL = "INSERT INTO ip_votes VALUES (NULL, '$ ip',' $ loc ', NOW (),' $ name ')";
$ Subsql = "select max (to_days (VoteTime) FROM ip_votes where ip = '$ ip '";
$ Stm = $ this-> odb-> query ($ subsql );
If (count ($ row = $ stm-> fetchAll () = 1)
{
$ Now = date ("Y-m-d H: I: s ");
$ Subsql = "SELECT to_days ('$ now ');";
$ Stm = $ this-> odb-> query ($ subsql)-> fetch ();
$ Time = $ stm [0]; // use the today time calculated by mysql
// Echo $ time. "<br> ";
// Echo $ row [0] [0];
If ($ time-$ row [0] [0] <1) // compare the maximum time in the table with the current time $ time
{
Echo "failed to vote. It takes one day to vote for the same ip address ";
Return;
}
}
// Echo $ SQL;
Echo "Vote successful! ";
$ This-> odb-> exec ($ SQL );
}
/**
* Add the row of the SelectName Field
*
* @ Param string $ name
* @ Param string $ label
* @ Param int $ count
*/
Public function addSelectName ($ name, $ label, $ count = 0)
{
$ SQL = "INSERT INTO count_voting VALUES ('$ name',' $ label', $ count );";
$ This-> odb-> exec ($ SQL );
}
/**
* Obtain the total voting results sorted by votes
*
* Sort by CountVotes field and return the count_voting table
*
* @ Param int $ n
*
*/
Public function getVotesSortByCount ($ n =-1)
{
$ SQL = "SELECT * FROM count_voting ORDER BY CountVotes DESC LIMIT 0, $ n ;";
If (-1 = $ n)
{
$ SQL = "SELECT * FROM count_voting ORDER BY CountVotes DESC ;";
}
// Echo $ SQL;
Return $ this-> odb-> query ($ SQL );
}
/**
* Obtain the voting result, sorted by votes, and grouped by tags
*
* Sort by CountVotes field and group by LabelName field. The count_voting table is returned.
*/
Public function getVotesGroupByLabel ()
{
$ SQL = "SELECT * FROM count_voting ORDER BY LabelName DESC ;";
// Echo $ SQL;
Return $ this-> odb-> query ($ SQL );
}
}
?>

The required functions are as follows:Copy codeThe Code is as follows: <? Php
/**
* Page Jump Function
* Implemented using js
* @ Param string $ url
*/
Function goToPgae ($ url)
{
Echo "<script language = 'javascript 'Type = 'text/javascript '> ";
Echo "window. location. href = '$ url '";
Echo "</script> ";
}
Function jsFunc ($ fun, $ arg = null)
{
Echo "<script language = 'javascript 'Type = 'text/javascript '> ";
Echo $ fun. "('$ arg ');";
Echo "</script> ";
}
Function jsFunc3 ($ fun, $ arg1 = null, $ arg2 = null, $ arg3 = null)
{
Echo "<script language = 'javascript 'Type = 'text/javascript '> ";
Echo $ fun. "('$ arg1', '$ arg2', '$ arg3 ');";
Echo "</script> ";
// Echo $ fun. "('$ arg1', '$ arg2', '$ arg3 ');";
}
Function isLoginNow ()
{
If ($ _ COOKIE ["user"] = '')
{
Return false;
}
Return true;
}
Function getClientIP ()
{
If ($ _ SERVER ["HTTP_X_FORWARDED_FOR"])
{
If ($ _ SERVER ["HTTP_CLIENT_IP"])
{
$ Proxy = $ _ SERVER ["HTTP_CLIENT_IP"];
}
Else
{
$ Proxy = $ _ SERVER ["REMOTE_ADDR"];
}
$ Ip = $ _ SERVER ["HTTP_X_FORWARDED_FOR"];
}
Else
{
If ($ _ SERVER ["HTTP_CLIENT_IP"])
{
$ Ip = $ _ SERVER ["HTTP_CLIENT_IP"];
}
Else
{
$ Ip = $ _ SERVER ["REMOTE_ADDR"];
}
}
Return $ ip;
}
// Obtain the ip address from 123
Function getIpfrom123cha ($ ip ){
$ Url = 'HTTP: // www.123cha.com/ip /? Q = '. $ ip;
$ Content = file_get_contents ($ url );
$ Preg = '/(? <= Main Site Data: <\/li> <li style = \ "width: pixel PX; \"> )(.*)(? = <\/Li>)/isU ';
Preg_match_all ($ preg, $ content, $ mb );
$ Str = strip_tags ($ mb [0] [0]);
// $ Str = str_replace ('','', $ str );
$ Address = $ str;
If ($ address = ''){
$ Address = 'unknown ';
}
Return $ address;
}
// Obtain the ip address location from Baidu
Function getIpfromBaidu ($ ip ){
$ Url = 'HTTP: // www.baidu.com/s? Wd = '. $ ip;
$ Content = file_get_contents ($ url );
$ Preg = '/(? <= <P class = \ "op_ip_detail \"> )(.*)(? = <\/P>)/isU ';
Preg_match_all ($ preg, $ content, $ mb );
$ Str = strip_tags ($ mb [0] [1]);
$ Str = str_replace ('','', $ str );
$ Address = substr ($ str, 7 );
If ($ address = ''){
$ Address = 'unknown ';
}
Return $ address;
}
?>

Then there is how the operations of the background administrator are done, mainly the function of adding a vote item, which has been implemented on the database. Basically, how to set pages is related to js. The page for adding a vote item is dynamic, as shown below:Copy codeThe Code is as follows: function addVote ()
{
Right. innerHTML = "Right. innerHTML + = "<label> voting item label <label> ";
AddInput ("right", "cLabelName", "region name ");
Right. innerHTML + = "<br> <label> voting item name <label> ";
AddInput ("right", "cSelectName", "school name ");
Right. innerHTML + = "<br> ";
Var args = '\'./add. php \ ', \ 'cselectname \', \ 'clabelname \'';
Var str = '<input type = button value = "\ u6dfb plus" onclick = "goToPage (' + args + ');"/> ';
Right. innerHTML + = str;
}
// Add a text box
Function addInput (parent, id, pla)
{
// Create input
Var input = document. createElement ("input ");
Input. type = "text ";
Input. id = id;
Input. placeholder = pla;
Document. getElementById (parent). appendChild (input );
}

Effect:

Clearing the voting items is similar, as shown below:

Add a vote item to pass the variable to the add. php page through the url.Copy codeThe Code is as follows: <? Php
Require_once '../api/func. php ';

If (! IsLoginNow ())
{
GoToPgae ("./index. php ");
}

$ Name = $ _ GET ["cSelectName"];
$ Label = $ _ GET ["cLabelName"];
// Echo $ name. "<br>". $ label;
Require_once '../api/OperatorVotingDB. php ';
$ Ovdb = new OperatorVotingDB ();
$ Ovdb-> addSelectName ($ name, $ label );
Require './header.htm ';
GoToPgae ("./admin. php? Page = add & auto = "." $ label "." & id = cLabelName & foc = cSelectName & msg = added successfully ");
?>

Below are two page Jump functions, js (the above func. php page Jump function is also implemented through js ).Copy codeThe Code is as follows: // js
Function goToPage (url, arg1, arg2)
{
Var a = document. getElementById (arg1). value;
Var B = document. getElementById (arg2). value;
Url + = '? '+ Arg1 +' = '+;
Url + = '&' + arg2 + '=' + B;
Window. location. href = url;
}

Function goToPage1 (url)
{
Window. location. href = url;
}

The modification and deletion function is not implemented. I should not implement that. js is similar to adding functions.

If you log on to the module, there will be a lot of online information. Is to submit a form, find the database, and return results. If the cookie is set successfully, the cookie detection function is added to every page in the background.

Front-end beautification
Index. on the php page, first obtain the voting items and votes through the database, and then display them (beautify the framework interface through css + div). Finally, click the vote button to submit the form and jump to vote. php page.

Css is copied to the Internet. My results are as follows:

This is a very small Information Management System, I have put the source code of this thing on github (https://github.com/hanxi/voting) up, you can freely download the changes can also download to the feet of the house (click to download ). You are welcome to reply to the discussion. This is not my strong point and I hope you can advise me if you have many shortcomings.

Author: Han XI (Han Xi's technology blog-blog Park)
Weibo: t.qq.com/hanxi1203
Source: hanxi.cnblogs.com

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.