I am wondering my class property $friend_username does not returning its value either it is public.
update
class Feed {
public static $friend_username;
// ONLINE FRIENDS LOGIC
public function online_friends(){
$friendsHTML = '';
$countOnlineFriends = '';
if(GetFriends($GLOBALS['log_username']) != false) {
$all_friends = GetFriends($GLOBALS['log_username']);
$orLogic = '';
foreach($all_friends as $key => $user){
if(IsBlocked($GLOBALS['log_username'],$user,true) == false){
$orLogic .= "username='$user' OR ";
}
}
$orLogic = chop($orLogic, "OR ");
$sql = "SELECT username, avatar, logged_in FROM users WHERE ($orLogic) AND logged_in = 1";
$query = mysqli_query($GLOBALS['db_conx'], $sql);
$friend_loggedIn = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$this->friend_username = $row["username"];
$friend_avatar = $row["avatar"];
$friend_loggedIn[] = $row["logged_in"];
$friend_pic = userImage($this->friend_username,$friend_avatar,'42','42',$link = false,$up = true);
$friendsHTML .= '<li><a href="#" onClick="chatbox(\''.$this->friend_username.'\',\''.getName($this->friend_username,true).'\');return false;">'.$friend_pic.' '.getName($this->friend_username,true).'</li>';
$countFriends = count($friend_loggedIn);
$countOnlineFriends = ($countFriends > 0) ? '<span class="online_friends animated">'.$countFriends.'</span>' : '';
}
}else{
$friendsHTML = 'No friends';
}
return "$countOnlineFriends|$friendsHTML";
}
public function update_chat() {
$id = '';
$messages = '';
$randUser = '';
$user = sanitize($this->friend_username);
$sql = "SELECT * FROM pm_chat WHERE (sender='$GLOBALS[log_username]' AND receiver='$user') OR (sender='$user' AND receiver='$GLOBALS[log_username]') ORDER BY datetime DESC";
$result = mysqli_query($GLOBALS['db_conx'],$sql) or die(mysqli_error($GLOBALS['db_conx']));
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user1 = $row['sender'];
$user2 = $row['receiver'];
$message = parseData($row['message']);
$did_read = $row['did_read'];
$datetime = $row['datetime'];
if ($user1 != $GLOBALS['log_username']) {
$randUser = $user1;
}elseif ($user2 != $GLOBALS['log_username']) {
$randUser = $user2;
}
if ($user1 == $GLOBALS['log_username'] && $user2 != $GLOBALS['log_username']) {
$messages .= '<li class="row" id="pm_row_'.$id.'"><div class="me">'.$message.'</div></li>';
}else{
$messages .= '<li class="row" id="pm_row_'.$id.'">'.userImage($randUser,getAvatar($randUser),28,28,$link = true,$up = true).'<div class="userfrnd">'.$message.'</div></li>';
}
}
return $this->friend_username."$id|$messages|$randUser";
// this is for ^^^^^^^ testing purpose
}
}
here is the other file where I am calling the other class method. And its content-type is text/event-stream
class update_chat extends SSEEvent {
public function update(){
//Here's the place to send data
$feed = new Feed();
return $feed->update_chat();
}
public function check(){
//Here's the place to check when the data needs update
return true;
}
}
Any idea or suggestion why this problem persist ?
thanks in advance.
If you are calling bar() in another file and then creating a new Foo in otherClass, you are not referencing the same instance of Foo. Either make $friend_username static and call it statically
public static $friend_username;
public function update(){
//Here's the place to send data
return Foo::$friend_username;
}
or at least make the function static
public static function bar() {}
public function update(){
//Here's the place to send data
return Foo::bar();
}
or pass in the instance of Foo to the function
public function update(Foo $Foo){
//Here's the place to send data
return $Foo->bar();
}
If you want to call a static method from within the same class, you have to use the self identifier (self::$var)
class Feed {
public static $friend_username = array();
// ONLINE FRIENDS LOGIC
public function online_friends(){
$friendsHTML = '';
$countOnlineFriends = '';
if(GetFriends($GLOBALS['log_username']) != false) {
$all_friends = GetFriends($GLOBALS['log_username']);
$orLogic = '';
foreach($all_friends as $key => $user){
if(IsBlocked($GLOBALS['log_username'],$user,true) == false){
$orLogic .= "username='$user' OR ";
}
}
$orLogic = chop($orLogic, "OR ");
$sql = "SELECT username, avatar, logged_in FROM users WHERE ($orLogic) AND logged_in = 1";
$query = mysqli_query($GLOBALS['db_conx'], $sql);
$friend_loggedIn = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push(self::$friend_username, $row["username"]);
$friend_avatar = $row["avatar"];
$friend_loggedIn[] = $row["logged_in"];
$friend_pic = userImage(self::$friend_username,$friend_avatar,'42','42',$link = false,$up = true);
$friendsHTML .= '<li><a href="#" onClick="chatbox(\''.self::$friend_username.'\',\''.getName(self::$friend_username,true).'\');return false;">'.$friend_pic.' '.getName(self::$friend_username,true).'</li>';
$countFriends = count($friend_loggedIn);
$countOnlineFriends = ($countFriends > 0) ? '<span class="online_friends animated">'.$countFriends.'</span>' : '';
}
}else{
$friendsHTML = 'No friends';
}
return "$countOnlineFriends|$friendsHTML";
}
public function update_chat() {
$id = '';
$messages = '';
$randUser = '';
$user = Feed::$friend_username;
foreach ($user as $key => $value) {
$user[$key] = sanitize($value);
}
//I leave it up to you to figure out how you want to deal with the array of users in this next line
$sql = "SELECT * FROM pm_chat WHERE (sender='$GLOBALS[log_username]' AND receiver='$user') OR (sender='$user' AND receiver='$GLOBALS[log_username]') ORDER BY datetime DESC";
$result = mysqli_query($GLOBALS['db_conx'],$sql) or die(mysqli_error($GLOBALS['db_conx']));
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user1 = $row['sender'];
$user2 = $row['receiver'];
$message = parseData($row['message']);
$did_read = $row['did_read'];
$datetime = $row['datetime'];
if ($user1 != $GLOBALS['log_username']) {
$randUser = $user1;
}elseif ($user2 != $GLOBALS['log_username']) {
$randUser = $user2;
}
if ($user1 == $GLOBALS['log_username'] && $user2 != $GLOBALS['log_username']) {
$messages .= '<li class="row" id="pm_row_'.$id.'"><div class="me">'.$message.'</div></li>';
}else{
$messages .= '<li class="row" id="pm_row_'.$id.'">'.userImage($randUser,getAvatar($randUser),28,28,$link = true,$up = true).'<div class="userfrnd">'.$message.'</div></li>';
}
}
return Feed::$friend_username."$id|$messages|$randUser";
// this is for ^^^^^^^ testing purpose
}
}
Well, since your are using the method mysqli_fetch_array, could it be that more than one element is returned and that the last one is empty?
BTW, I don't understand why you are making a single variable attribution inside a while statement. Supposedly, the last running (if some) will overwrite the variable's value.
Another observation, on the second code. If you are calling the bar() method right off the bat, shoudn't the variable be empty anyway? I understand that $friend_username is only assigned inside the foo() method.
Related
I get an error in my file "checkusername.php".
The error I get is:
( ! ) Fatal error: Call to a member function get() on null in
C:\wamp\www\Cocolani\php\req\checkusername.php on line 4
There is a "checkusername.php" file :
<?php
include_once("../../includes/db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$username = isset($_POST['username']) ? mysqli_real_escape_string($_POST['username']) : "";
$password = isset($_POST['password']) ? mysqli_real_escape_string($_POST['password']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : '';
$birthdate = isset($_POST['birthdate']) ? mysqli_real_escape_string($_POST['birthdate']) : "";
$firstname = isset($_POST['firstname']) ? mysqli_real_escape_string($_POST['firstname']) : "";
$lastname = isset($_POST['lastname']) ? mysqli_real_escape_string($_POST['lastname']) : "";
$sex = isset($_POST['sex']) ? mysqli_real_escape_string($_POST['sex']) : "";
$tribeid = isset($_POST['clan']) ? mysqli_real_escape_string($_POST['clan']) : "";
$mask = isset($_POST['mask']) ? mysqli_real_escape_string($_POST['mask']) : "";
$mask_color = isset($_POST['maskcl']) ? mysqli_real_escape_string($_POST['maskcl']) : "";
$lang_id = isset($_POST['lang_id']) ? addslashes($_POST['lang_id']) : 0;
$error = '';
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$reg_ok = true;
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'"; // for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
if ($email_check_ok == false) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
/*if ($reg_ok && $email != '') {
// get number of already registered number of registrations with this email address
$sql = "SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
$registered_num_emails = $row->registered_num_emails;
$sql = "SELECT max_num_account_per_email from `cc_def_settings`";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
// it's possible to create new registration using this email address
if ($registered_num_emails >= $row->max_num_account_per_email) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}*/
////////
// echo 'error=111';
// $reg_ok = false;
////////
if ($reg_ok) {
// check for swear words
$db->setQuery("SELECT COUNT(*) as counter from `cc_swear_words` where INSTR('".$username."', `name`)");
$res2 = $db->loadResult();
if ((int)($res2->counter) > 0) { // swear word founded!
$sql = "SELECT * FROM `cc_translations` WHERE caption='USERNAME_NOT_PERMITTED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) {
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ((int)($res->counter) > 0) { // swear word founded!
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) echo 'result=true';
?>
The problem on line 4 which is :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
There is a "settings.php" :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "pass1234";
$db_name = "cocolani_battle";
$appsecret = "80f730a73ac60417c36c341bc975f6f1";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
and there is a "db.php" :
<?php
/*
Usage
$db = new database($dbname);
for selects:
$db->setQuery("SELECT * FROM `table`")
$resultArray = $db->loadResults();
$db->setQuery("SELECT * FROM `table` WHERE `primary_id` = '1'");
$resultObject = $db->loadResult();
for inserts:
$db->setQuery("INSERT INTO `table` (`id`, `example`) VALUES ('1', 'abc')");
if (!$db->runQuery()) {
echo $db->getError();
}
*/
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "pass1234";
var $_DBname = "cocolani_battle";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
}
/*if ($_SERVER["SERVER_ADDR"] == '127.0.0.1') {
$url_root = "http://cocolani.localhost";
} else {
$url_root = "http://dev.cocolani.com";
}*/
?>
How can I fix this error?
As I mentioned in my comment, you can either use the variables you defined in your settings.php:
$db = new database($db_name, $db_server, $db_user, $db_password, $db_urlroot); // You didn't define $db_urlroot anywhere, but you can define it
OR hard-code it into your class. You're not using the variables you pass in anyway, so there's no need to ask for them.
public function __construct() {
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!
So I've been stuck on this for quite a while, surprisingly the update and delete functions work just fine, however I cannot make the CREATE function work properly. Please have a look at it and tell me what I'm doing wrong
<-------------- Entire model for admin panel-------------->>>>>>>> Connection to DB is working fine---------->>>>>>>>>>>
<?php
include_once "Model.php";
class ModelPages extends Model {
public function get($key) {
$sql = "SELECT * from pages where page_key = '$key'";
$row = '';
$page = Null;
foreach ($this->pdo->query($sql) as $row) {
$page = $row;
}
// echo "<pre>";
// var_dump($page);
// exit;
return $page;
}
public function getAll() {
$statement = $this->pdo->prepare("SELECT * from pages Where Id > 3");
$result = $statement->execute();
$pages = array();
if($result) {
$pages = $statement->fetchAll(PDO::FETCH_ASSOC);
}
return $pages;
}
public function updatePage($params=array()) {
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$pageId = isset($params['page_key']) ? $params['page_key'] : null;
$pageTitle = isset($params['page_title']) ? $params['page_title'] : null;
$pageBody = isset($params['page_body']) ? $params['page_body'] : null;
if ($pageId == null) {
return 'No page id provided';
}
$sql = "UPDATE " . $tableName . " SET
title = :title,
body = :body
WHERE page_key = :page_key";
$statement = $this->pdo->prepare($sql);
$statement->bindParam(':title', $pageTitle, PDO::PARAM_STR);
$statement->bindParam(':body', $pageBody, PDO::PARAM_STR);
$statement->bindParam(':page_key', $pageId, PDO::PARAM_INT);
$result = $statement->execute();
return $result;
}
public function deletePage($pageId) {
// build sql
$sql = "DELETE FROM pages WHERE id = " . intval($pageId);
$statement = $this->pdo->prepare($sql);
$result = $statement->execute();
return $result;
}
public function createPage($params=array()){
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$page_key = isset($params['page_key']) ? $params['page_key'] : 'page_key';
$pageTitle = isset($params['page_title']) ? $params['page_title'] : 'page_title';
$pageBody = isset($params['page_body']) ? $params['page_body'] : 'page_body';
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
// prepare query for execution
$statement = $this->pdo->prepare($sql);
// bind the parameters
$statement->bindParam(':page_key', $_POST['page_key']);
$statement->bindParam(':title', $_POST['title']);
$statement->bindParam(':body', $_POST['body']);
// specify when this record was inserted to the database
// Execute the query
$result = $statement->execute();
return $result;
}
}
<?php
include 'controllers/controller.php';
include 'models/Model.php';
include 'models/ModelPages.php';
<------------------------ADMIN CONTROller----------------------->>>>>>>>>>>>
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
// TODO: update DB
$tableData['page_body'] = $_POST['body'];
$tableData['table'] = 'pages';
$tableData['page_title'] = $_POST['title'];
$tableData['page_key'] = $_POST['page_key'];
$response = $ModelPages->updatePage($tableData);
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&success=true");
}
}
if(isset($_GET['page_key'])) {
// by default we assume that the key_page exists in db
$error = false;
$page = $ModelPages->get($_REQUEST['page_key']);
// if page key does not exist set error to true
if($page === null) {
$error = true;
}
// prepare data for the template
$data = $page;
$data["error"] = $error;
// display
echo $this->render2(array(), 'header.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2($data, 'admin_update_page.php');
echo $this->render2(array(), 'footer.php');
} else {
// case: delete_page
if(isset($_GET['delete_page'])) {
$response = $ModelPages->deletePage($_GET['delete_page']);
if($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&deleted=true");
}
}
}
//Get table name and make connection
if(isset($_POST['submit'])) {
$page_key = $_POST['page_key'];
$page_title = $_POST['title'];
$page_body = $_POST['body'];
$response = $ModelPages->createPage();
if($response=TRUE){
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&created=true");
}
}
}
// load all pages from DB
$pages = $ModelPages -> getAll();
// display
echo $this->render2(array(), 'header_admin.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2(array("pages"=> $pages), 'admin_view.php');
echo $this->render2(array(), 'footer.php');
}
}
?>
Since you have if(isset($_POST['page_key']) on the top:
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
...
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?
}
and it is used to call $response = $ModelPages->updatePage($tableData);
your code never reach the part with good values at the bottom:
if(!isset($_POST['page_key'])) {
...
$response = $ModelPages->createPage($tableData);
So my simple but not the best suggestion is use extra parameter when POST like action. so you can check:
if(isset($_POST['action']) && $_POST['action']=='update') {
...
} elseif (isset($_POST['action']) && $_POST['action']=='create') {
...
} etc...
hope this will help you for now :-)
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
$tablename is not in scope when the statement above is executed. And you've got no error handling in the code.
I'm working on an advanced search but got error
Fatal error: Cannot access empty property *$this->$Personnummer*
Here is my controller:
<?php
include 'c:/wamp/www/mvc/model/SearchProcessor.php';
// if the user clicks the submit button, it sends its name values here and if not empty, binds them to $data.
if(isset($_POST['button'])) {
if($_POST['name'] !='');
{
$data['name'] = $_POST['name'];
}
if($_POST['lastname'] !='');
{
$data['lastname'] = $_POST['lastname'];
}
if($_POST['Personnummer_search'] !='');
{
$data['Personnummer'] = $_POST['Personnummer_search'];
}
if($_POST['Kon_search'] !='');
{
$data['Kon_search'] = $_POST['Kon_search'];
}
if($_POST['Anvands_search'] !='');
{
$data['Anvands_search'] = $_POST['Anvands_search'];
}
if($_POST['Lan_search'] !='');
{
$data['Lan_search'] = $_POST['Lan_search'];
}
if($_POST['Processormodell_search'] !='');
{
$data['Processormodell_search'] = $_POST['Processormodell_search'];
}
if($_POST['Sida_search'] !='');
{
$data['Sida_search'] = $_POST['Sida_search'];
}
if($_POST['utlamnat_search'] !='');
{
$data['utlamnat_search'] = $_POST['utlamnat_search'];
}
if($_POST['ProcessorSerie_search'] !='');
{
$data['ProcessorSerie_search'] = $_POST['ProcessorSerie_search'];
}
if($_POST['Tillverkare_search'] !='');
{
$data['Tillverkare_search'] = $_POST['Tillverkare_search'];
}
$displayResults = new SearchProcessor($db,$data);
$Results = $displayResults->getSearchResult();
Here is the model:
<?php
require_once 'Database.php';
//This class is for searching for patient and their processors
class SearchProcessor extends Database {
private $Personnummer;
private $TheKon;
private $TheLan;
private $name;
private $TheLastname;
private $TheProcessor;
private $TheAnvands;
private $TheSida;
private $TheUtlamnat;
private $TheSerienummer;
private $TheTillverkare;
//The constructor of both the parent and child class
function __construct(mysqli $db, $data)
{
parent::__construct($db);
//set data
$this->setData($data);
// get search result
$this->getSearchResult();
}
//Sets the data
function setData($data)
{
$this->name = $data['name'];
$this->TheLastname = $data['lastname'];
$this->Personnummer = $data['Personnummer'];
$this->TheKon = $data['Kon_search'];
$this->TheAnvands = $data['Anvands_search'];
$this->TheLan = $data['Lan_search'];
$this->TheProcessor = $data['Processormodell_search'];
$this->TheSida =$data['Sida_search'];
$this->TheUtlamnat =$data['utlamnat_search'];
$this->TheSerienummer = $data['ProcessorSerie_search'];
$this->TheTillverkare = $data['Tillverkare_search'];
}
//This function searches each column regarding patient and its processors.
function getSearchResult() {
$where = array();
$where[] = "Patient.Patient LIKE '%".$this->$Personnummer."%'"; //<--- ERROR Cannot access empty property
$where[] = "person.Namn LIKE '%".$this->name."%'";
$where[] = "person.Efternamn LIKE '%".$this->TheLastname."%'";
$where[] = "person.Kon LIKE '%".$this->TheKon."%'";
$where[] = "processorpatient.Sida LIKE '%".$this->TheSida."%'";
$where[] = "person.Lan LIKE '%".$this->TheLan."%'";
$where[] = "processorpatient.Tillverkare LIKE '%".$this->TheTillverkare."%'";
$where[] = "processorpatient.Processor LIKE '%".$this->TheProcessor."%'";
$where[] = "processorpatient.Utlamnat LIKE '%".$this->TheUtlamnat."%'";
$where[] = "processorpatient.Anvands LIKE '%".$this->TheAnvands."%'";
$where[] = "processorpatient.Serienummer LIKE '%".$this->TheSerienummer."%'";
if(count($where)) // here it counts the amount of $where and a extends the query to search deeper into the database.
{
$Data = array();
$sql = "Select * from patient left join person on person.Personnummer = patient.Patient left join processorpatient on processorpatient.patientv = patient.Patient
WHERE ".implode(" AND ",$where);
if(!$result = $this->mysqli->query($sql)) {
throw new exception("Error: Can not execute the query.");
} else {
$Count = $result->num_rows;
if($Count>0)
{
for($i=0; $i<$Count; $i++)
{
$Data[$i] = $result->fetch_assoc();
}
}
}
return $Data;
}
}
}
What I want to be doing is assign user input $_POST[''] to variables $data[''] in the controller. And then pass it the model class that is supposed to bind it with their own private variables in which is giving value to the query. But I'm getting error Cannot access empty property $this->$Personnummer at the model
access variable without $ as like same as you defined above
$this->Personnummer = $data['Personnummer'];
so access this like
$where[] = "Patient.Patient LIKE '%".$this->Personnummer."%'";
I am working on an Item Inventory Web App. I want users should be able to add and assign item to a user. Each user is entitled to one item at a time. If, say, user a already has an item assigned and you want to add more item, the system should lodge an error that will tell you
to withdraw the item be issuing a new one but the errors are not getting lodged in the error[] array even though it shows that the array is not empty. It only echo out the serial number a = 1 and a++ but the text is not there.
class.inc.php
class Summary {
public $result;
public $conn;
public $SQ;
public $q;
public $updateDB;
public $checkDB;
public $returned_result;
public $a;
public $data;
public $col;
public function __construct(){
$this->conn = new PDO('mysql:host=localhost; dbname=dB', 'root', '');
$this->conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function updateDB($coloumn, $data, $id){
$SQ = "UPDATE mytable SET $coloumn = ? WHERE staffID = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $id);
if ($q->execute()){
$success = 'Record updated successfully';
};
return $success;
}
public function checkDB($col, $data){
$status = 'Active';
$SQ = "SELECT surname FROM mytable WHERE $col = ? AND status = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $status);
$q->execute();
if($result = $q->fetch(PDO::FETCH_BOTH)){
$a = $result[0];
if ($a == ''){
$this->returned_result = 'N';
}
else {
$this->returned_result = "This item (". $data . ") is in use by ". $a . ". Please widthraw the item";
}
}
return $this->returned_result;
}
}
index.php:
include('class.inc.php');
$summary = new Summary;
$error = array();
if(isset($_POST['saveRecord']) ) {
$system_name = strtoupper ( $_POST['system_name'] );
$result =$summary->checkDB('systemName', $system_name); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('systemName', $system_name, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
$system_serial_number = strtoupper ( $_POST['system_serial_number'] );
$result =$summary->checkDB('CPUSerial', $system_serial_number); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('CPUSerial', $system_serial_number, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
}
if(isset($_POST['saveRecord']) && !empty( $error ) ) {
echo "<div class = 'text-error'>";
$a = 1;
foreach ($error as $err){
echo '<p>' . $a . '. ' .$err . '</p>';
$a++;
}
echo "</div>";
}
Any help will be greatly appreciated. And what am I doing wrong with regards to OOP way of programming?