Design and implementation of Php+mysql voting system share _php instances

Source: Internet
Author: User
Tags dsn get ip preg
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 CodeThe code is 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 statistics ';
-- --------------------------------------------------------
--
--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 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 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 (ten) not NULL COMMENT ' Administrator username ',
' passwd ' char (+) not NULL COMMENT ' login password MD5 value '
) Engine=innodb DEFAULT charset=utf8 comment= ' user table ';
--
--Dump the data in the table ' user '
--
INSERT into ' user ' (' name ', ' passwd ') VALUES
(' Ttxi ', ' 700469ca1555900b18c641bf7b0a1fa1 '),
(' Jitttanwa ', ' adac5659956d68bcbc6f40aa5cd00d5c ');
--
--Restricting the exported table
--
--
--Restriction 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 CodeThe code is as follows:
/**
* Operation Database
* Encapsulate PDO to make it easy for you to operate
*/
Class Operatordb
{
Basic information for 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 to create a database connection object $db
}
catch (Pdoexception $e)
{
Die ("
Database connection failed (creater PDO error! ): ". $e->getmessage ()."
");
}
}
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 CodeThe code is as follows:
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 operations class to perform the clear database operation
*/
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];//The Today time calculated using MySQL
echo $time. "
";
echo $row [0][0];
if ($time-$row [0][0]<1]//The maximum time in the table and the current time is compared to
{
echo "Voting failed, the same IP needs a day to vote";
Return
}
}
Echo $sql;
echo "Vote succeeded!";
$this->odb->exec ($sql);
}
/**
* Add a row for 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);
}
/**
* Get total votes, sorted by number of votes
*
* Sort by countvotes field, return to 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);
}
/**
* Get voting status, sort by number of votes and group by label results
*
* Sort by countvotes field and group by LabelName Field, return to 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 also required
Copy CodeThe code is as follows:
/**
* Page Jump function
* Using JS implementation
* @param string $url
*/
function Gotopgae ($url)
{
echo "";
}
function Jsfunc ($fun, $arg =null)
{
echo "";
}
function jsFunc3 ($fun, $arg 1=null, $arg 2=null, $arg 3=null)
{
echo "";
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 the IP from 123 check
function Getipfrom123cha ($IP) {
$url = ' http://www.123cha.com/ip/?q= '. $ip;
$content = file_get_contents ($url);
$preg = '/(? <= main Station master data:<\/li>
  • ) (. *) (?=<\/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;
    }
    Get IP location from Baidu
    function Getipfrombaidu ($IP) {
    $url = ' http://www.baidu.com/s?wd= '. $ip;
    $content = file_get_contents ($url);
    $preg = '/(? <=

    ) (. *) (?=<\/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= "

    Add voting items

    ";
    right.innerhtml+= "Voting Items tab";
    Addinput ("Right", "Clabelname", "region name");
    right.innerhtml+= "
    Voting Item Name";
    Addinput ("Right", "Cselectname", "School Name");
    right.innerhtml+= "
    ";
    var args = ' \ './add.php\ ', \ ' cselectname\ ', \ ' clabelname\ ';
    var str = '';
    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 ballot is similar to the following:

    Adding a voting item is a URL that passes a variable to the add.php page.
    Copy CodeThe code is as follows:
    Require_once '. /api/func.php ';

    if (!isloginnow ())
    {
    Gotopgae ("./index.php");
    }

    $name = $_get["Cselectname"];
    $label = $_get["Clabelname"];
    echo $name. "
    ". $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 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+ ' = ' +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+div 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.