PHP plus MySQL voting system design and implementation sharing

Source: Internet
Author: User
Tags dsn get ip preg
This article to you to share is the PHP plus MySQL voting system design and implementation of the sharing, the need for friends can refer to

PHP Voting system design and implementation, the need for friends can refer to the code and database results design, the last script home provides the source code download

System is small, the process of completing this system I divided three steps
• Database Design
• System Framework Design
• Front-end Landscaping

design of the database
Design Three sheets: poll results table (count_voting), voter record (ip_votes), User table
The poll results are used to count the final voting records, and I've got 4 fields for it: The name of the item being voted (Selectname), the tag name (LabelName) of the voting item (the role of the category), the number of votes (countvotes).

The Voter record table is used to register the voter's IP (IP), geolocation (location), polling time (Votetime), and the name of the voting item (selectname). Then I'll add an ID to it.

The user table is used primarily for administrators, including the user name (name) and password (passwd).

The SQL script that generated the table is as follows:

Copy the Code code as follows:

The structure of the----table ' count_voting '--DROP table IF EXISTS ' count_voting '; CREATE TABLE IF not EXISTS ' count_voting ' (' selectname ' varchar (+) NOT null, ' labelname ' varchar (+) NOT NULL, ' Countvot Es ' bigint (unsigned) not NULL, UNIQUE key ' Selectname ' (' selectname '), key ' countvotes ' (' countvotes '), key ' Countvotes _2 ' (' countvotes '), KEY ' Countvotes_3 ' (' countvotes ')) engine=innodb DEFAULT Charset=utf8 comment= ' voting statistics '; The structure of the--------------------------------------------------------------table ' ip_votes '--DROP table IF EXISTS ' ip_votes '; CREATE TABLE IF not EXISTS ' ip_votes ' (' ID ' bigint (a) unsigned not NULL auto_increment COMMENT ' voter number: self-increment ', ' IP ' varchar ( Not NULL COMMENT ' voter IP ', ' location ' varchar (+) NOT null COMMENT ' voter position ', ' votetime ' datetime NOT NULL, ' Selectname ' varchar (+) 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 C Ountvotes = countvotes + 1 WHERE selectname = NEW. Selectname//DELIMITER; The structure of the--------------------------------------------------------------table ' user '-DROP table IF EXISTS ' user '; CREATE TABLE IF not EXISTS ' user ' (' name ' varchar () ' "Not null COMMENT ' Admin user name ', ' passwd ' char (+) ' NOT null COMMENT ' login password MD5 value ') engine=innodb default Charset=utf8 comment= ' User table '; The data in the----Dump table ' user '--INSERT into ' user ' (' name ', ' passwd ') VALUES (' Ttxi ', ' 700469ca1555900b18c641bf7b0a1fa1 '), (' Jittt Anwa ', ' adac5659956d68bcbc6f40aa5cd00d5c ');  ----Restrict exported tables------limit table ' ip_votes '--ALTER table ' ip_votes ' ADD CONSTRAINT ' ip_votes_ibfk_1 ' FOREIGN KEY (' Selectname ') REFERENCES ' count_voting ' (' Selectname ') on the DELETE CASCADE on UPDATE CASCADE;

As you can see from the script, I created a trigger that adds 1 to the Countvotes field in the Count_voting table when inserting data into the Ip_votes table. And then the last sentence is to set the external correlation word.
Frame design
The Operatordb class is used for manipulating databases, and the Operatorvotingdb class is used for this system-specific set of operations.
Using PDO to manipulate the database, I'll simply encapsulate it:

Copy the Code code as follows:

/** * Operation Database * Encapsulates PDO to make it easy for you to operate */class Operatordb {///connection database basic information private $dbms = ' mysql ';//database type, for developers, use different databases, just change this. pr Ivate $host = ' localhost '; Database host name Private $dbName = ' voting '; The database used is private $user = ' voting '; Database connection user name private $passwd = ' voting '; The corresponding 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 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) {} }


The information that connects the database is encapsulated to facilitate the subsequent operation.

Copy the Code code as follows:

<?php require_once ' operatordb.php ';  Class Operatorvotingdb {Private $odb, public function __construct () {$this->odb = new Operatordb (),} public function __destruct () {$this->odb = null;}/** * empties all tables in voting data * Call Database operations class, perform clear database operation */Public Function cleartables () {$sqls = Array ("TRUNCATE ip_votes;", "TRUNCATE count_voting;"); $this->odb->exec ($sqls [0]); $this->odb->exec ($sqls [1]); }/** * Resets the Countvalues field in the Count_voting table to 0 * */Public Function resetcountvalues () {$sql = "UPDATE count_voting SET Countvo tes = 0; "; $this->odb->exec ($sql); }/** * Vote * Write information to ip_votes table * @param type $IP * @param type $loc * @param type $time * @param type $name */public Functio N 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];//uses MySQL to calculate the Today time//echo $time. " <br> "; echo $row [0][0]; if ($time-$row [0][0]<1]//The maximum time in the table and the current time is at the moment of the comparison {echo "poll failed, the same IP needs to be a day to vote"; return;}} Echo $sql; echo "Vote succeeded!"; $this->odb->exec ($sql); /** * Add selectname Field Line * * @param string $name * @param string $label * @param int $count */Public function Addselectna Me ($name, $label, $count =0) {$sql = "INSERT into count_voting VALUES (' $name ', ' $label ', $count);" $this->odb->exe C ($sql); /** * Get total votes, sort results by number of votes * * Sorted by countvotes field, return 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 C Ount_voting ORDER by Countvotes DESC; ";} Echo $sql; return $this->odb->query ($sql); }/** * Get voting, sort by number of votes and GROUP by label results * * Sorted by countvotes field and grouped by LabelName field, return to count_voting table */Public Function GEtvotesgroupbylabel () {$sql = "select * count_voting ORDER by labelname DESC;";//Echo $sql; return $this->odb-& Gt;query ($sql); }}?> The following functions are required to copy code code as follows: <?php/** * page Jump function * Using JS implementation * @param string $url */function Gotopgae ($url) {echo "<s Cript 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, $arg 1=null, $arg 2=null, $arg 3=null) {echo "<script language= ' javascript ' type= ' text/ JavaScript ' > '; echo $fun. " (' $arg 1 ', ' $arg 2 ', ' $arg 3 '); "; echo "</script>"; echo $fun. " (' $arg 1 ', ' $arg 2 ', ' $arg 3 '); 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"];}} r Eturn $ip; }//from 123 Get IP function Getipfrom123cha ($ip) {$url = ' http://www.123cha.com/ip/?q= '. $ip; $content = file_get_contents ($ URL); $preg = '/(? <= main data: <\/li><li style=\ "width:450px;\" >) (. *) (?=<\/li>)/isu '; Preg_match_all ($preg, $content, $MB); $str = Strip_tags ($mb [0][0]); $str = Str_replace (', ', ', $str); $address = $str; if ($address = = ") {$address = ' not specified ';} return $address; }//From Baidu Get IP location 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 = ' not specified ';} return $address; }?>


Then is the background administrator's operation how to get, mainly to add the function of voting items, the operation of the database above has been implemented. The following is basically the page how to set, related to JS. The page that added the voting entries is dynamic, as follows:

Copy the Code code as follows:

function Addvote () {right.innerhtml= "

Effect:

Clearing the ballot is similar to the following:

Adding a voting item is a URL that passes a variable to the add.php page.

Copy the Code code 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= add Success ");?>

The following is the function of two jump page, JS (The jump page function in func.php is also implemented by JS).

Copy the Code code as follows:

JS function GoToPage (url,arg1,arg2) {var a = document.getElementById (arg1). value; var b = document.getElementById (arg2 ). Value; URL + = '? ' +arg1+ ' = ' +a; URL + = ' & ' +arg2+ ' = ' +b; Window.location.href=url; } function GoToPage1 (URL) {window.location.href=url;}


There is no implementation of the Modify Delete feature. I should not go to the realization of that, JS words and add the same function.

Login module Words online a lot, imitation of. is to submit the form, find the database, and return the results. Success sets cookies, and every page in the background adds the ability to detect cookies.

Front-End Landscaping
index.php Page First operation database to get votes and votes, then show (through Css+p beautify the frame interface what), and finally click the Voting button to submit the form, jump to the vote.php page.

CSS, I have copied the Internet. I made the following results:

This thing is a very small information management system, I have put the source of this thing on GitHub (https://github.com/hanxi/voting) up, you can freely download the changes can also go to the script home download (click to download). Welcome to the reader to reply to the exchange, this is not my strong points, there are many shortcomings also hope to advise.

Author: 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.