I have a MySQL table named "orders". I want to make functions so I can easily access how many orders was added during Last: Hours, Day, Week, Month and Year.
If I don't require file dbconfig.php in each function than I get ERROR :(
So far the code below works exactly as I want but I think its possible to shorten it?
<?php
function count_db_last_hour(){
require("../dbconfig.php");
$sql = "SELECT * FROM orders WHERE checkdate >= date_sub(now(), INTERVAL 1 HOUR) ORDER BY checkdate DESC";
$result = $connect->query($sql);
$connect->close();
return $result->num_rows;
}
function count_db_last_week(){
require("../dbconfig.php");
$sql = "SELECT * FROM orders WHERE checkdate >= date_sub(now(), INTERVAL 1 WEEK) ORDER BY checkdate DESC";
$result = $connect->query($sql);
$connect->close();
return $result->num_rows;
}
function count_db_last_day(){
$sql = "SELECT * FROM orders WHERE checkdate >= date_sub(now(), INTERVAL 1 DAY) ORDER BY checkdate DESC";
require("../dbconfig.php");
$result = $connect->query($sql);
$connect->close();
return $result->num_rows;
}
function count_db_last_month(){
$sql = "SELECT * FROM orders WHERE checkdate >= date_sub(now(), INTERVAL 1 MONTH) ORDER BY checkdate DESC";
require("../dbconfig.php");
$result = $connect->query($sql);
$connect->close();
return $result->num_rows;
}
function count_db_last_year(){
$sql = "SELECT * FROM orders WHERE checkdate >= date_sub(now(), INTERVAL 1 YEAR) ORDER BY checkdate DESC";
require("../dbconfig.php");
$result = $connect->query($sql);
$connect->close();
return $result->num_rows;
}
echo count_db_last_hour() . '<br>' . count_db_last_day() . '<br>' . count_db_last_month() . '<br>' . count_db_last_year() ;
?>
Is it possible to shorten this code? Thank you for helping out.
UPDATED:
If I don't require dbconfig.php inside function I get ERROR:
PHP Notice: Undefined variable: connect in /home/test2.php on line 9
PHP Fatal error: Uncaught Error: Call to a member function query() on null in /home/test2.php:9 Stack trace:
#0 /home/test2.php(35): count_db_last_hour()
#1 {main} thrown in /home/test2.php on line 9
The dbconfig.php file has this code:
<?php
$servername = "localhost";
$username = "ordzxq_usar";
$password = "9ir3Grd_fXz";
$dbname = "store_orders";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
?>
include, then put it in the global scope