Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/* MySQL 数据库名称 */
define('DB_NAME', 'wordpress');
/* MySQL 数据库用户名 */
define('DB_USER', 'root');
/* MySQL 数据库密码 */
define('DB_PASSWD', 'root');
/* MySQL 主机 */
define('DB_HOST', 'localhost');
/**
* @Author: prpr
* @Date: 2016-01-22 21:28:52
* @Last Modified by: prpr
* @Last Modified time: 2016-01-22 23:23:09
*/
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWD, DB_NAME);
$conn->query("SET names UTF8");
if ($conn->connect_error) {
die("Unable to connect to database. ".$conn->connect_error."<br />
Check if database config correct in the file header.");
}
header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json; charset=utf-8");
if (!isset($_GET['action']) || $_GET['action'] == "get") {
echo getCount();
} else {
echo like();
}
function like() {
global $conn;
$ip = getClientIp();
$ip_result = $conn->query("SELECT * FROM votes WHERE ip='$ip'");
if ($ip_result->num_rows == 0) {
$conn->query("INSERT INTO votes (ip) values ('$ip')");
$json['success'] = 1;
$json['msg'] = 'Successfully liked.';
return json_encode($json);
} else { // repeated ip
$json['success'] = 0;
$json['msg'] = 'Repeated IP address.';
return json_encode($json);
}
}
function getCount() {
global $conn;
if ($result = $conn->query("SELECT COUNT(*) FROM votes")) {
$json['success'] = 1;
$json['like'] = $result->fetch_array()[0];
return json_encode($json);
}
die($conn->connect_error);
}
function getClientIp() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
/**
* Create tables automatically
* This function cant be access by default
*
* @return void
*/
function createTables() {
global $conn;
$sql = "CREATE TABLE IF NOT EXISTS `votes` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`ip` varchar(40) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=121 DEFAULT CHARSET=utf8;";
if ($conn->query($sql)) {
echo "Tables successfully created.";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.