Design and implementation of Php+mysql voting system sharing _php instance

Source: Internet
Author: User
Tags dsn get ip preg
The system is not large, I completed the process of three steps
• Database Design
• System Framework Design
• Front End Landscaping

the design of the database
Design Three tables: poll results tables (count_voting), Voter Records (ip_votes), User table (users)
The results of the poll were used to count the final voting records, and I gave it 4 fields: the name of the item (SELECTNAME), the voting label name (LabelName), the number of votes (countvotes).

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

User tables are used primarily for administrators, including user name (name) and password (passwd).

The SQL script that generates the table is as follows:
Copy 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,
' Countvotes ' 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 tables ';
-- --------------------------------------------------------
--
--The structure of the table ' Ip_votes '
--
DROP TABLE IF EXISTS ' ip_votes ';
CREATE TABLE IF not EXISTS ' ip_votes ' (
' ID ' bigint (unsigned not NULL auto_increment COMMENT ' voter serial number: self-increasing ',
' 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 inserts on ' Ip_votes '
For each ROW UPDATE count_voting SET countvotes = 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 username ',
' 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 '),
(' Jitttanwa ', ' adac5659956d68bcbc6f40aa5cd00d5c ');
--
--Restricting the exported table
--
--
--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 association word.
Frame design
The Operatordb class is used to manipulate the database, and the Operatorvotingdb class is used for the system-specific set of operations.
Using PDO to manipulate the database, I simply encapsulate it:
Copy Code code as follows:

/**
* Operation Database
* Package PDO to make it easy to operate
*/
Class Operatordb
{
Basic information about connecting to a database
Private $dbms = ' mysql '; Database type, for developers, use a different database, just change this.
Private $host = ' localhost '; Database host Name
Private $dbName = ' voting '; The database used
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, which 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)
{
}
}

The information of the connection database is encapsulated in to facilitate the subsequent operation.
Copy 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;
}
/**
* Empty all tables in the voting data
*
* Call the database action class to perform the operation of the clear database
*/
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 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 MySQL to calculate today time
echo $time. " <br> ";
echo $row [0][0];
if ($time-$row [0][0]<1)//table $time Comparison of the maximum time and present time
{
echo "Failed to vote, the same IP need to vote every other day";
Return
}
}
Echo $sql;
echo "Vote success!"
$this->odb->exec ($sql);
}
/**
* Add the line 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);
}
/**
* To obtain the total vote, by the number of votes ordered by the results
*
* Sort 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 Count_voting order by countvotes DESC;";
}
Echo $sql;
return $this->odb->query ($sql);
}
/**
* Results of voting, sorted by number of votes and grouped by label
*
* Sort by countvotes field and group by LabelName field, return count_voting table
*/
Public Function Getvotesgroupbylabel ()
{
$sql = "SELECT * from Count_voting order by labelname DESC;";
Echo $sql;
return $this->odb->query ($sql);
}
}
?>

The following functions are required
Copy Code code as follows:

<?php
/**
* Page Jump function
* Use JS to implement
* @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, $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"];
}
}
return $IP;
}
Get IP from 123 check
function Getipfrom123cha ($IP) {
$url = ' http://www.123cha.com/ip/?q= '. $ip;
$content = file_get_contents ($url);
$preg = '/(<= site 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 clear ';
}
return $address;
}
Get IP 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 = ' not clear ';
}
return $address;
}
?>

Then is the backstage administrator's operation how to get, mainly is adds the voting item the function, the operation database above already realizes. The back is basically how the page settings, related to JS. The page that adds the voting item is dynamic, as follows:
Copy Code code as follows:

function Addvote ()
{
Right.innerhtml= "right.innerhtml+= "<label> voting label <label>";
Addinput ("Right", "Clabelname", "region name");
right.innerhtml+= "<br><label> voting title <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:

Empty the ballot is similar to the following:

Adding a voting item is passing the variable to the add.php page by URL.
Copy 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 ");
?>

Below is two jump page function, JS (above func.php jump page function is also through JS implementation).
Copy 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 deletion feature. I should not go to achieve that, JS words and add functionality almost.

Login module Words online a lot, imitate. is to submit the form, find the database, and return the results. A cookie is set for success, and the ability to detect cookies is added to each page in the background.

Front End Landscaping
index.php page first to manipulate the database to get votes and votes, and then show (through the css+div to beautify the frame interface), and finally click on the voting button to submit the form, jump to the vote.php page.

CSS words I have copied the Internet. I made the following effect:

This thing is a very small information management system, I have put the source code of this thing to GitHub (https://github.com/hanxi/voting) up, you can download any changes can also be downloaded to the Cloud Habitat community (click to download). Welcome readers to reply to the exchange, this aspect is not my strong points, there are many deficiencies also hope advice.

Author: Han Xi (Han-Xi's technology blog-blog Park)
Micro Blog: 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.