I have this code in OOP Php
include ('connection.php');
class NestedSet
{
/*Properties*/
/**
* Mysqli object
* #var object
*/
protected $db;
/**
* Name of the database table
* #var string
*/
public $table = 'tree';
/**
* Primary key of the database table
* #var string
*/
public $pk = 'id';
/**
* Namefield in the database table
* #var unknown_type
*/
public $name = 'name';
/*Methods*/
/**
* Stores a Mysqli object for further use
* #param object $mysqli Mysqli object
* #return boolean true
*/
public function __construct() {
$this->db = mysqliConn::init();
return true;
}
protected static $instance = NULL;
// public static function get_instance()
// {
// //if ( NULL === self::$instance )
// // self::$instance = new self;
// // return self::$instance;
// }
/**
* Creates the root node
* #param string $name Name of the new node
* #return boolean true
*/
public function createRootNode($name) {
$this->db->query("LOCK TABLES " . $this->table . " WRITE");
$sql = "SELECT rgt FROM " . $this->table . " ORDER BY rgt DESC LIMIT 1";
$result = $this->db->query($sql);
if ($this->db->affected_rows == 0) {
$lft = 1;
$rgt = 2;
} else {
$obj = $result->fetch_object();
$lft = $obj->rgt + 1;
$rgt = $lft + 1;
}
$sql = "INSERT INTO " . $this->table . " (" . $this->name . ", lft, rgt) VALUES ('" . $name . "', " . $lft . ", " . $rgt . ");";
$this->db->query($sql);
$this->db->query("UNLOCK TABLES");
return true;
}
}
?>
I create a new object for the class NestedSet in an other file called index.php
<?php
include("nested_set.php");
$nested = new NestedSet(); //Create a NestedSet object
$nested->createRootNode('root');
?>
I can write on db but the $rgt and $lft stays 2 and 1;
and this error is displayd :
"Notice: Undefined property: mysqliConn::$affected_rows in C:\wamp\www\hr-test\nested_set.php on line 67"
Any idea on what im doing wrong?
Thank you!!
CODE FOR connection.php
<?php
define('SERVER', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'hr_test2');
class mysqliConn
{
private static $instance;
private $connection;
private function __construct()
{
$this->connection = new mysqli(SERVER,USERNAME,PASSWORD,DATABASE);
}
public static function init()
{
if(is_null(self::$instance))
{
self::$instance = new mysqliConn();
}
return self::$instance;
}
public function __call($name, $args)
{
if(method_exists($this->connection, $name))
{
return call_user_func_array(array($this->connection, $name), $args);
} else {
trigger_error('Unknown Method ' . $name . '()', E_USER_WARNING);
return false;
}
}
}
?>
Because a mysqli->query() returns a mysqli_result object which will contain information about the result of the query you need to use $result and not $this->db->
Also the mysqli_result object does not contain an affected_rows property you should use the num_rows property which does exist, but on the $result object instead.
You can also simplify the concatenation of the query string you create, although you should really use prepared statements.
public function createRootNode($name) {
$this->db->query("LOCK TABLES " . $this->table . " WRITE");
$sql = "SELECT rgt FROM " . $this->table . " ORDER BY rgt DESC LIMIT 1";
$result = $this->db->query($sql);
// if ($this->db->affected_rows == 0) {
if ($result->num_rows == 0) {
$lft = 1;
$rgt = 2;
} else {
$obj = $result->fetch_object();
$lft = $obj->rgt + 1;
$rgt = $lft + 1;
}
$sql = "INSERT INTO {$this->table} ( {$this->name}, lft, rgt)
VALUES ('$name', $lft , $rgt)";
$this->db->query($sql);
$this->db->query("UNLOCK TABLES");
return true;
}
Related
I have trouble understanding OOP...
Lets say I wanted to create a page that adds a new user to a database and wanted to work with classes.
For that scenario i'd create a form with a function.
There are forms for each CRUD functionality - renderHTMLFormAddUser() :
...
<form action="" method="POST" >;
<label>Shopname*</label><br>;
<input type="text" name="shopname" class="input_wide" required><br>;
<label>Username*</label><br>;
<input type="text" name="username" class="input_wide" required><br>;
<input type="submit" value="add" name="submit" >
...
a DataBaseConnector class:
class DataBaseConnector
{
protected $con;
public function __construct()
{
$this->con=mysqli_connect('mariaDB','root','123456','produktmuster');
}
public function getConnection()
{
return $this->con;
}
public function __destruct()
{
$this->con->close();
}
}
and a QueryDatabase class that requires the DataBaseConnector connection as a transfer parameter in its constructor:
class QueryDatabase
{
private $con;
public function __construct(DataBaseConnector $con)
{
$this->con = $con;
}
public function addUser($shopname,$username)
{
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
$result = mysqli_query($this->con->connect(), $sql);
return $result;
}
To get the $_POST values in the QueryDatabase add User function, i'd need to declare variables like so:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
But is there a better way to do so?
Like maybe renderHTMLFormAddUser()->'shopname'.
Im just trying to understand what is the cleanest way to code in this scenario.
Because using a function to render the forms the adduser.php would look something like this:
$createuserform=new Forms();
$createuserform->renderHTMLFormAddUser();
$shopname= $_POST['shopname']; // this is what confuses me, you'd have to look into the
$username= $_POST['username']; // renderHTMLFormAddUser() function to see the code
$db = new DataBaseConnector();
$query= new QueryDatabase();
$query->addUser($shopname,$username)
Should I just create an own page that posts the form to a page that then uses the data?
In the beginning i simply used no transfer parameters with the addUser function, and it started with declaring the $_POSTs:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
...
But I was told it was unsafe to do so - in that regard, I sanitize my data but for the sake of easier example i stripped away all the unnecessary code.
Should I take a completely different approach, just would like to know the cleanest way to add form input data into a database.
Well, there are many approaches to do this. You can also do my OOPs approach:
Make a define.php to set the constant variables & database connection variables:
define.php
define("DB_HOSTNAME", "localhost");
define("DB_USERNAME", "your_username");
define("DB_PASSWORD", "your_password");
define("DB_NAME", "your_databasename");
define("custom_variable", "custom_variable_value");
define("baseurl", "https://localhost/myproject/");
Then, make dbase.php, to create a dynamic SQL function:
You don't need to change this file. You just need to call this class. This file work as the core file of the system.
Dbase.php
<?php session_start();
date_default_timezone_set("Asia/Karachi");
require_once("define.php");
Class Dbase
{
private $Host = DB_HOSTNAME;
private $UserName = DB_USERNAME;
private $Password = DB_PASSWORD;
private $DBname = DB_NAME;
private $connDb = false;
public $LastQuery = null;
public $AffectedRows = 0;
public $InsertKey = array();
public $InsertValues = array();
public $UpdateSets = array();
public $id;
public function __construct()
{
$this->connect();
}
protected function connect()
{
$this->connDb = #mysqli_connect($this->Host, $this->UserName, $this->Password);
if (!($this->connDb)) {
die('Database Connection Failed.<br>' . mysql_error($this->connDb));
} else {
$Select = mysqli_select_db($this->connDb,$this->DBname);
if (!$Select) {
die('Database Selection Failed.<br>' . mysql_error($this->connDb));
}
}
mysqli_set_charset($this->connDb,'utf8');
}
public function close()
{
if (!mysqli_close($this->connDb)) {
die('Closing Connection Failed.<br>');
}
}
public function escape($value)
{
if (function_exists('mysql_real_escape_string')) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
} else {
if (!get_magic_quotes_gpc()) {
$value = addcslashes($value);
}
}
return $value;
}
public function query($sql)
{
$query = $sql;
$result = mysqli_query($this->connDb,$sql);
// $this->displayQuery($result);
return $result;
}
public function displayQuery($result)
{
if (!$result) {
$output = 'Database Query Failed' . mysql_error($this->connDb) . '<br>';
$output .= 'Last Query was' . $this->LastQuery;
die($output);
} else {
$this->AffectedRows = mysqli_affected_rows($this->connDb);
}
}
public function fetchAll($sql)
{
$result = $this->query($sql);
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[] = $row;
}
// mysql_free_result($result);
return $output;
}
public function fetchOne($sql)
{
$output = $this->fetchAll($sql);
return $output;
// return array_shift($output);
}
public function prepareInsert($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->InsertKey[] = $key;
$this->InsertValues[] = $this->escape($value);
}
}
}
public function insert($table = null)
{
if (!empty($table) && !empty($this->InsertKey) && !empty($this->InsertValues)) {
$sql = "insert into '{$table}' ('";
$sql .= implode("','", $this->InsertKey);
$sql .= "') values ('";
$sql .= implode("','", $this->InsertValues);
$sql .= "')";
if ($this->query($sql)) {
$this->id = $this->lastId();
return true;
}
return false;
} else {
return false;
}
}
public function prepareUpdate($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->UpdateSets[] = "`{$key}` = '" . $this->escape($value) . "'";
}
}
}
public function update($table = null, $id = null, $whereId)
{
if (!empty($table) && !empty($id) && !empty($this->UpdateSets)) {
$sql = "update `{$table}` set";
$sql .= implode(",", $this->UpdateSets);
// $sql.="where id='".$this->escape($id)."'";
$sql .= "where '" . $whereId . "'='" . $this->escape($id) . "'";
return $this->query($sql);
} else {
return false;
}
}
public function lastId()
{
return mysqli_insert_id($this->connDb);
}
public function TotalNumberOfRecords($sql)
{
$result = $this->query($sql);
$output = mysqli_num_rows($result);
return $output;
}
public function GetServerInfo()
{
return mysqli_get_server_info();
}
}
Create a Query.php file. This file work as your model file as in MVC.
Query.php
<?php include "Dbase.php";
Class Query extends Dbase
{
public function __construct()
{
$this->connect();
date_default_timezone_set("Asia/Karachi");
}
public function getData($idlevelOne)
{
$sql = "SELECT * FROM `table` where level_one_id=$idlevelOne ORDER BY `sorting` ASC";
$result = $this->fetchAll($sql);
return $result;
}
/*For Insert & Edit, use this fucntion*/
public function editMember($email, $phone, $address, $city, $country, $zipcode, $id)
{
$sql = "UPDATE `members` SET `email` = '" . $email . "', `phone` = '" . $phone . "', `address` = '" . $address . "'
, `city` = '" . $city . "', `country` = '" . $country . "', `zip_code` = '" . $zipcode . "'
WHERE `id` = '$id'";
$result = $this->query($sql);
return $result;
}
}
Now, you just need to call the Query class in your PHP files to get the data.
<?php
include "Query.php";
$ObjQuery = new Query();
$ObjQuery->getData(1);
I'm trying to fetch data from php via PDO to then receive a JSON object (json_encode) to have something to work with on frontend. Try as I might, the only data I receive from MySQL query are the usernames of users who added the messages (tweets), see below:
Tweet class:
class Tweet extends User {
private $id;
private $userId;
private $text;
private $creationDate;
public function __construct() {
$this->id = -1;
$this->userId = null;
$this->text = null;
$this->creationDate = null;
}
function getId() {
return $this->id;
}
function getUserId() {
return $this->userId;
}
function getText() {
return $this->text;
}
function getCreationDate() {
return $this->creationDate;
}
function setUserId($userId) {
$this->userId = $userId;
}
function setText($text) {
$this->text = $text;
}
function setCreationDate($creationDate) {
$this->creationDate = $creationDate;
}
static public function loadTweetById(PDO $pdo, $id) {
$stmt = $pdo->prepare("SELECT * FROM Messages WHERE message_id=:id");
$result = $stmt->execute([
'id' => $id
]);
if ($result === true && $stmt->rowCount() > 0) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$loadedTweet = new Tweet();
$loadedTweet->id = $row['message_id'];
$loadedTweet->userId = $row['user_id'];
$loadedTweet->text = $row['message_text'];
$loadedTweet->creationDate = $row['message_datetime'];
return $loadedTweet;
}
return null;
}
static public function loadAllTweetsByUserId(PDO $pdo, $id) {
//$stmt = $pdo->prepare("SELECT * FROM Messages WHERE user_id=:id");
$stmt = $pdo->prepare("SELECT "
. "Users.username, "
. "Messages.message_text, "
. "Messages.message_datetime "
. "FROM "
. "Messages "
. "JOIN "
. "Users "
. "ON Users.id=Messages.user_id "
. "WHERE `user_id`=:id "
. "ORDER BY Messages.message_datetime DESC");
$result = $stmt->execute([
'id' => $id
]);
//var_dump($stmt->rowCount());
if ($result === true && $stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$loadedTweet = new Tweet();
//echo $loadedTweet->id = $row['message_id'] . '<br>';
echo $loadedTweet->userId = $row['username'] . '<br>';
echo $loadedTweet->text = $row['message_text'] . '<br>';
echo $loadedTweet->creationDate = $row['message_datetime'] . '<br>';
echo "<br>";
//return $loadedTweet;
}
return null;
}
}
static public function loadAllTweets(PDO $pdo) {
$sql = "SELECT * FROM Messages JOIN Users ON Users.id=Messages.user_id ORDER BY Messages.message_datetime DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$tweets = $stmt->fetchAll(PDO::FETCH_OBJ);
$tweetsList = [];
if ($stmt !== false && $stmt->rowCount() > 0) {
foreach ($tweets as $dbTweet) {
$tweet = new Tweet($pdo);
$tweet->id = $dbTweet->message_id;
$tweet->userId = $dbTweet->user_id;
$tweet->text = $dbTweet->message_text;
$tweet->creationDate = $dbTweet->message_datetime;
$tweet->getUsername = $dbTweet->username;
$tweetsList[] = $tweet;
}
return $tweetsList;
} else {
return null;
}
}
public function saveToDB(PDO $pdo) {
//sprawdza czy robimy insert czy update
if ($this->id == -1) { // if -1, robimy insert
//przygotowanie zapytania
//$userId = $_SESSION['userId'];
$sql = "INSERT INTO `Messages`(`user_id`, `message_text`) VALUES (:user_id, :message_text)";
$prepare = $pdo->prepare($sql);
//wyslanie zapytania do bazy z kluczami i wartosciami do podmienienia
$result = $prepare->execute([
//uzywa userId zapisanego w sesji
'user_id' => $this->userId,
'message_text' => $this->text
]);
// pobranie ostatniego ID dodanego rekordu i przypisanie do ID w tabeli Users
//$this->id = $pdo->lastInsertId();
return (bool) $result;
}
}
function loadAllTweets from Tweet class (returns an array of Tweet objects):
static public function loadAllTweets(PDO $pdo) {
$sql = "SELECT * FROM Messages JOIN Users ON Users.id=Messages.user_id ORDER BY Messages.message_datetime DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$tweets = $stmt->fetchAll(PDO::FETCH_OBJ);
$tweetsList = [];
if ($stmt !== false && $stmt->rowCount() > 0) {
foreach ($tweets as $dbTweet) {
$tweet = new Tweet();
$tweet->id = $dbTweet->message_id;
$tweet->userId = $dbTweet->user_id;
$tweet->text = $dbTweet->message_text;
$tweet->creationDate = $dbTweet->message_datetime;
$tweet->getUsername = $dbTweet->username;
$tweetsList[] = $tweet;
}
return $tweetsList;
} else {
return null;
}
}
mainpage.php
<?php
include_once '../../bootstrap.php';
header('Content-Type: application/json');//return json header
$username = $_SESSION['username'];
$tweets = Tweet::loadAllTweets($connection);
$jsonTweets = [];
foreach ($tweets as $tweet) {
$jsonTweets[] = json_decode(json_encode($tweet), true);
}
$response = ["tweets" => $jsonTweets,
"success" => $username];
echo json_encode($response);
ajax
$.ajax({
url: "../admin/ajax/mainpage.php",
dataType: 'json'
})
.done(function (response) {
console.log(response.tweets);
})
.fail(function (response) {
console.log(response);
});
Any insight on what I'm doing wrong is greatly appreciated.
The private properties of the Tweet class are not visible to json_encode and therefore not included in the json. Make them public or implement \JsonSerializable with a custom jsonSerialize implementation, e.g.
class Tweet implements \JsonSerializable
{
// ...
public function jsonSerialize()
{
return [
'foo' => $this->foo,
'bar' => $this->bar
];
}
}
More on visibility: http://docs.php.net/language.oop5.visibility
The not so obvious thing is that your static method loadTweetData can indeed access the private props because the objects are of the same class.
Note off topic: Having your Tweet model extend User is a little awkward because the Tweet is not a User (violates Liskov substitution principle).
i have created pagination for my product page! while write down code. i have got this error
Error code image screenshot
Strict standards: Non-static method DB_Connection::obj_db() should not be called statically in D:\wamp\www\project\ali\models\product.php on line 147
require_once 'db_connection.php';
require_once 'brand.php';
class Product extends DB_Connection{
public $productID;
public $product_name;
public $description;
public $product_features;
public $unit_price;
public $quantity;
public $view_count;
public $product_image;
public $featured;
public $brand;
public function __construct() {
$this->brand = new Brand();//composition
}
public function get_product($view_update = FALSE) {
$obj_db = $this->obj_db();
$query = "select * "
. "from products_full "
. "where productID = '$this->productID'";
$result = $obj_db->query($query);
if($obj_db->errno){
throw new Exception("Select product Error - $obj_db->error -$obj_db->errno");
}
if($result->num_rows == 0){
throw new Exception("Product not found");
}
$data = $result->fetch_object();
if($view_update){
$data->view_count++;
$query_update = "update products set "
. "view_count = view_count+1 "
. "where `productID` = '$this->productID'";
$r2 = $obj_db->query($query_update);
if($obj_db->affected_rows == 0){
}
}
$this->productID = $data->productID;
$this->product_name = $data->product_name;
$this->description = $data->description;
$this->product_features = $data->product_features;
$this->product_image = $data->product_image;
$this->unit_price = $data->unit_price;
$this->quantity = $data->quantity;
$this->view_count = $data->view_count;
$this->brand->brandID = $data->brandID;
$this->brand->brand_name = $data->brand_name;
$this->brand->brand_image = $data->brand_image;
}
public static function get_products($start = -1, $count = 0, $type = "all", $brandID = 0) {
//$obj_db = $this->obj_db();
$obj_db = self::obj_db();
$query = "select * from `products` ";
if($brandID > 0){
$query .= " where brandID = $brandID";
}
$types = array("all", "top", "new");
if(!in_array($type, $types)){
$type = "all";
}
if($type == "top"){
$query .= " order by view_count desc";
}
if($type == "new"){
$query .= " order by productID desc";
}
if($start > -1 && $count > 0){
$query .= " limit $start, $count";
}
$result = $obj_db->query($query);
if($obj_db->errno){
throw new Exception("Select products Error - $obj_db->error -$obj_db->errno");
}
if($result->num_rows == 0){
throw new Exception("Product(s) not found");
}
$products = array();
while($data = $result->fetch_object()){
$temp = new Product();
$temp->productID = $data->productID;
$temp->product_name = $data->product_name;
$temp->description = $data->description;
$temp->product_features = $data->product_features;
$temp->product_image = $data->product_image;
$temp->unit_price = $data->unit_price;
$temp->quantity = $data->quantity;
$temp->view_count = $data->view_count;
//$temp->brand = TRUE;
$products[] = $temp;
}
return $products;
}
public static function pagination($item_per_page = 6, $brandID = 0){
$obj_db = self::obj_db();
$query = "select count(*) 'count' from `products`";//alias
if($brandID > 0){
$query .= " where brandID = $brandID";
}
$result = $obj_db->query($query);
if($result->num_rows == 0){
throw new Exception("Product(s) not found");
}
$data = $result->fetch_object();
$total_items = $data->count;
$page_count = ceil($total_items/$item_per_page);
$page_nums = array();
for($i = 1, $j = 0 ; $i <= $page_count; $i++, $j+=$item_per_page){
$page_nums[$i] = $j;
}
return $page_nums;
}
First let me give you an example and explain why this is happening.
class A{
public function foo(){
echo "foo";
}
public static function bar(){
// If you call the foo function like this:
// error: Strict standards: Non-static method A::foo() should not be called statically
//self::foo();
// That means it should be called like this:
(new A)->foo();
}
}
A::bar();
The difference between static and non-static is that the first one doesn't need initialization so you can call the classname then append :: to it and call the method immediately. like this:
ClassName::method();
and if the method is not static you need to initialize it like this:
$obj = new ClassNmae();
$onj->method();
However in PHP 5.4 you can use this syntax instead for faster calling:
(new ClassName)->method();
That being said, this is what you need to change in your code:
// your code
public function get_product($view_update = FALSE) {
$obj_db = $this->obj_db();
// your code
}
public static function get_products($start = -1, $count = 0, $type = "all", $brandID = 0) {
$obj_db = (new DB_Connection)->obj_db();
// your code
}
public static function pagination($item_per_page = 6, $brandID = 0){
$obj_db = (new DB_Connection)->obj_db();
// your code
}
i had done mistake, i have created static function for pagination. i have forgot to add static on db connection page!
protected static function obj_db(){
and
public static function get_products($start = -1, $count = 0, $type = "all", $brandID = 0) {
//$obj_db = $this->obj_db();
$obj_db = self::obj_db();
thanks all of them, who have guide me as well!
I am new to OOP and want some help I have this some code that selects and fetches data from a database but I don't know how to display fetched data.
/**
* Connect to mysql database
*
* #return bool;
*/
public function Connect() {
$settings = database_settings();
$connect = new mysqli($settings->host, $settings->user, $settings->password, $settings->database);
if (!$connect->connect_errno) {
return $connect;
} else {
return false;
}
}
/**
* Prepare a mysqli query
*
* #return bool;
*/
public function statement($query) {
if (!empty($query)) {
$this->query = $query;
return true;
}
return false;
}
/**
* Execute a mysqli query and store result in memory
*
* #return bool;
*/
public function execute() {
$this->database = $this->Connect();
if (isset($this->query) && !empty($this->query)) {
$this->database->set_charset("utf8");
$this->exe = $this->database->query($this->query);
if (!isset($this->exe)) {
throw new DatabaseException("{$this->database->error} \n {$this->query} ");
}
if (isset($this->database->insert_id)) {
$this->last_id = $this->database->insert_id;
}
unset($this->query);
$this->database->close();
return true;
}
return false;
}
/**
* Prepare a query to select data from database
*
* #params = array();
* $params['from'] = names of table
* $params['params'] = names of columns which you want to select
* $params['wheres'] = specify a selection criteria to get required records
*
* #return bool;
*/
public function select($params, $multi = '') {
if (is_array($params)) {
if (!isset($params['params'])) {
$parameters = '*';
} else {
$parameters = implode(', ', $params['params']);
}
$order_by = '';
if (!empty($params['order_by'])) {
$order_by = "ORDER by {$params['order_by']}";
}
$where = '';
if (isset($params['wheres']) && is_array($params['wheres'])) {
$where = implode(' ', $params['wheres']);
}
$wheres = '';
if (!empty($params['wheres'])) {
$wheres = "WHERE({$where})";
}
$limit = '';
if (!empty($params['limit'])){
$limit = "LIMIT {$params['limit']}";
}
$query = "SELECT {$parameters} FROM `{$params['from']}` {$wheres} {$order_by} {$limit};";
$this->statement($query);
if ($this->execute()) {
return $this->fetch($multi);
}
}
return false;
}
/**
* Fetch the data from memory that is stored during execution;
*
* #params = $data = (ture if you want to fetch all data , or flase if only one row)
*
* #return bool;
*/
public function fetch($data = false) {
if (isset($this->exe)) {
if ($data !== true) {
if ($fetch = $this->exe) {
return arrayObject($fetch->fetch_assoc());
}
}
if ($data === true) {
if ($fetch = $this->exe) {
while ($all = $fetch->fetch_assoc()) {
$alldata[] = arrayObject($all);
}
}
if (isset($alldata) && !empty($alldata)) {
return arrayObject($alldata);
}
}
}
return false;
}
then i select data but can't display them:
$params['from'] = 'category';
$params['order_by']= 'id';
$params['wheres'] = 'active="1"';
$params['limit']= '1';
$connect->select($params);
I want to extend this class (which I downloaded) to suit my own needs. When I run call this class I get an error complaining that there is an unexpected = in the constructor.
define("HIT_OLD_AFTER_SECONDS", 4 * 7 * 24 * 3600);
class PHPCount extends DatabaseObject {
protected static $table_name = "hits";
protected static $db_fields = array('pageid','isunique', 'hitcount','english_id');
public $pageid;
public $isunique;
public $hitcount;
public $english_id;
public static $article_id;
function __construct(){
return PHPCount::article_id = PHPCount::get_article_id();
}
public static function set_article_id($articleid){
PHPCount::article_id = $articleid;
}
public static function get_article_id(){
return PHPCount::article_id;
}
public static function AddHit($pageID, $visitorID){
HitTest::Cleanup();
self::CreateCountsIfNotPresent($pageID);
if(HitTest::UniqueHit($pageID, $visitorID)){
self::CountHit($pageID, true);
HitTest::LogHit($pageID, $visitorID);
}
self::CountHit($pageID, false);
}
/*
* Returns (int) the amount of hits a page has
* $pageID - the page identifier
* $unique - true if you want unique hit count
*/
public static function GetHits($pageID, $unique = false){
global $database;
self::CreateCountsIfNotPresent($pageID);
$pageID = $database->escape_value($pageID);
$unique = $unique ? '1' : '0';
$q = "SELECT hitcount FROM hits WHERE ";
$q .= get_article_id()=$pageID;
$q .=" AND isunique={$unique}";
$getHitCount = static::find_by_sql($q);
if(sizeof($getHitCount) >= 1){
foreach($getHitCount as $hit){
return (int)$hit->hitcount;
}
}else{
die("Fatal: Missing hit count from database!");
}
}
/*
* Returns the total amount of hits to the entire website
* When $unique is FALSE, it returns the sum of all non-unique hit counts
* for every page. When $unique is TRUE, it returns the sum of all unique
* hit counts for every page, so the value that's returned IS NOT the
* amount of site-wide unique hits, it is the sum of each page's unique
* hit count.
*/
public static function GetTotalHits($unique = false){
//global $phpcount_con;
$total = 0;
$unique = $unique ? '1' : '0';
$q = "SELECT hitcount FROM hits WHERE isunique={$unique}";
$count = static::find_by_sql($q);
foreach($count as $hit){
$total += (int)$hit->hitcount;
}
return $total;
}
private static function CountHit($pageID, $unique){
global $database;
$unique = $unique ? '1' : '0';
$safeID = $database->escape_value($pageID);
$q ="UPDATE hits SET hitcount = hitcount + 1 WHERE ";
$q .=get_article_id()=$safeID;
$q .=" AND isunique={$unique}";
mysqli_query($database->connection,$q);
}
private static function CreateCountsIfNotPresent($pageID){
global $database;
$pageID = $database->escape_value($pageID);
$q = "SELECT pageid FROM hits WHERE ";
$q .=get_article_id()=$pageID;
$q .=" AND isunique='0'";
$createCount = static::find_by_sql($q);
if($q === false || sizeof($createCount) < 1){
$sql ="INSERT INTO hits(";
$sql .=get_article_id();
$sql .=", isunique, hitcount) VALUES(";
$sql .=$pageID;
$sql .=", '0', '0')";
mysqli_query($database->connection,$sql);
}
//check unique row
$q ="SELECT "get_article_id();
$q .=" FROM hits WHERE ";
$q .=get_article_id()=$pageID;
$q .=" AND isunique='1'";
$createCount = static::find_by_sql($q);
if($q === false || sizeof($createCount) < 1){
$sql ="INSERT INTO hits (";
$sql .=get_article_id();
$sql .=", isunique, hitcount) VALUES('$pageID', '1', '0')"
mysqli_query($database->connection,$sql);
echo mysqli_error($database->connection);
}
}
}
Access to static class variables require a $-sign like here:
PHPCount::$article_id
Thus, at least these methods need to be changed.
// I'd propose to pass the article ID as a parameter here
function __construct( $theArticleID ){
PHPCount::$article_id = $theArticleID;
}
public static function set_article_id($articleid){
PHPCount::$article_id = $articleid;
}
public static function get_article_id(){
return PHPCount::$article_id;
}