Obligatory suggestion, Don't use mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You should change the function name to get_total hits, as it makes no sense, and the scope of the database connection wont be available within functions, your need to pass it to it or use global to access it, this makes it bad practice but for example
<?php
function get_total_hits(){
global $db; // or whatever the variable for mysql_connect() is
$query_run = mysql_query("SELECT *
FROM hits_counter") or die(mysql_error());
return mysql_num_rows($query_run);
}
//perhaps what ip_exists should be...
function ip_exists(){
global $db; // or whatever the variable for mysql_connect() is
$query_run = mysql_query("SELECT *
FROM hits_counter
WHERE ip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."'
LIMIT 1") or die(mysql_error());
if(mysql_num_rows($query_run) == 1){
return true;
}else{
return false;
}
}
?>
And now for the better way todo it using PDO. Make a class that handles all your requests to the database for that table, then your be able to call the methods you want to get the data from that table.
<?php
//Open a mysql database connection using PDO
try {
$db = new PDO("mysql:host=127.0.0.1;dbname=yourtable", 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch (PDOException $e){
die('Cannot connect to mySQL server, Reason:'.$e->getMessage());
}
class hits_counter{
function __construct(PDO $db){
$this->db = $db;
}
function get_total_hits(){
$sql = $this->db->prepare('SELECT COUNT(1) as total_hits
FROM hits_counter');
$sql->execute();
$result = $sql->fetch(PDO::FETCH_ASSOC);
return $result['total_hits'];
}
function add_hit(){
$sql = $this->db->prepare('INSERT INTO hits_counter
(ip) VALUES (?)');
$sql->execute(array($_SERVER['REMOTE_ADDR']));
...
...
}
function hits_by_ip(){
...
...
}
}
$hits = new hits_counter($db);
echo $hits->get_total_hits();
?>
get me?