PHP Class not Returning Result - php

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?

Related

Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4

I'm still a beginner programmer , so I hope you give the solution step by step.
I'm trying to make a private server for a flash game and i have a problem that I don't know how can I solve it at all .
I wanna connect the game with the database , and when someone tries to make an account (register) in the game , the account data supposed to be saved in the database ( like: username,password,mask color,birth date,register date,etc...) but it doesn't happen
The file which is responsible about this step is called " register.php" and
I keep getting this error :
Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4
the problem is in this line :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
and this is "register.php" :
<?php
include_once("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"));
$FROM_EMAIL = $obj->getEmailFrom();
function generateTribeCurrency($ID, $db) {
// $db = new database();
// get init purse amount
$db->setQuery("SELECT init_purse_amount FROM `cc_def_settings`");
$row = $db->loadResult();
$init_purse_amount = $row->init_purse_amount;
// load tribe info
$db->setQuery("SELECT * FROM `cc_tribes`");
$tribeinfo = $db->loadResults();
$newstr = array();
foreach ($tribeinfo as $i) {
if ($ID == $i->ID) array_push($newstr, $init_purse_amount); else array_push($newstr, 0);
}
$newstr = implode(",", $newstr);
return $newstr;
}
$hackchk = false;
foreach($_POST as $POST) {
$POST = mysqli_real_escape_string($POST);
}
function remove_bad_symbols($s) {
return preg_replace(
array(0=>'#/#', 1=>'#\\\#', 2=>'#;#', 3=>'#{#', 4=>'#}#', 5=>'#<#', 6=>'#>#', 7=>'###', 8=>'#\'#', 9=>'# #', 10=>'#"#') // patterns
, '' // replacements
, $s);
}
$username = isset($_POST['username']) ? remove_bad_symbols($_POST['username']) : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$birthdate = isset($_POST['birthdate']) ? $_POST['birthdate'] : "";
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$sex = isset($_POST['sex']) ? $_POST['sex'] : "";
$tribeid = isset($_POST['clan']) ? $_POST['clan'] : "";
$mask = isset($_POST['mask']) ? $_POST['mask'] : "";
$mask_color = isset($_POST['maskcl']) ? $_POST['maskcl'] : "";
$lang_id = isset($_POST['lang_id']) ? $_POST['lang_id'] : 0;
$error = '';
$purse = generateTribeCurrency((int) $tribeid, $db);
// 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 = "";
$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";
}
// 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 ($username && $email && $sex && $birthdate) {
if ($email_check_ok) {
if ($res->counter == "0") {
// check that there are no registrations from this same IP in the last 2 hours
$db->setQuery("SELECT COUNT(*) as counter FROM `cc_userreginfo` WHERE IP='".$_SERVER['REMOTE_ADDR']."' AND (DATE_SUB(CURDATE(), INTERVAL 2 HOUR)<register_date)");
$regcheck = $db->loadResult();
if (($regcheck != null && (int)($regcheck->counter) == 0) || $hackchk == false) {
// get number of already registered number of registrations with this email address
$query = $db->setQuery("SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'");
$row = $db->loadResult();
$already_registered_num_emails = $row->registered_num_emails;
// get max number of accounts per email from settings table
$query = $db->setQuery("SELECT max_num_account_per_email from `cc_def_settings`");
$row = $db->loadResult();
$max_num_account_per_email = $row->max_num_account_per_email;
if ($already_registered_num_emails < $max_num_account_per_email) {
$uniqid = uniqid();
$newreq = "INSERT INTO `cc_user` (`ID`,`username`, `password`, `email`, `birth_date`, `first_name`, `last_name`, `sex`, `about`, `mask`, `mask_colors`, `clothing`, `tribe_ID` , `money`, `happyness`, `rank_ID`, `status_ID`, `lang_id`, `register_date`, uniqid, permission_id) VALUES ";
$newreq .= "(NULL, '{$username}', '{$password}', '{$email}', '{$birthdate}', '{$firstname}' , '{$lastname}', '{$sex}', '', '{$mask}', '{$mask_color}', '', '{$tribeid}', '{$purse}', 50, 0, 3, '{$lang_id}', NOW(), '{$uniqid}', 4)";
$db->setQuery($newreq);
$res = $db->runQuery();
if ($res) {
// add registration info into the userreginfo table as well.
$iid = $db->mysqlInsertID();
$db->setQuery("INSERT INTO `cc_userreginfo` (`ID`, `user_id`, `register_IP`, `register_date`, `last_update`) VALUES (NULL, ".$iid.",'".$_SERVER['REMOTE_ADDR']."', NOW(), NOW())");
$res2 = $db->runQuery();
$counter = ($regcheck != null) ? $regcheck->counter : 0;
echo 'response=true&reg='.$counter;
// ----------------------------------
// send confirmation email
// ----------------------------------
$cur_lang = ($lang != "") ? substr($lang, 1)."/" : "";
$msg = $obj->getTranslation(-13, $lang, "email_templates", "id", "content");
$msg = str_replace("%FIRST_NAME%", $firstname, $msg);
$msg = str_replace("%LAST_NAME%", $lastname, $msg);
$msg = str_replace("'", "'", $msg);
$msg = str_replace("%CONFIRM%", 'confirm', $msg);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
$headers .= 'From: '.$FROM_EMAIL."\r\n";
//mail($email, $obj->getTranslation(-13, $lang, "email_templates", "id", "subject"), $msg, $headers);
include "../../admin/php_mailer/class.phpmailer.php";
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $msg;
$body = eregi_replace("[\]",'',$body);
$mail->SetFrom($FROM_EMAIL);
$mail->AddAddress($email);
$mail->Subject = $obj->getTranslation(-13, $lang, "email_templates", "id", "subject");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
die("Mailer Error: " . $mail->ErrorInfo);
} else {
//echo "Message sent!";
}
// ----------------------------------
} else {
echo 'response=false';
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGISTER_LATER'");
$res = $db->loadResult();
echo 'errorhide='.urlencode($res->{"name".$lang});
}
} else {
// 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});
}
} else {
//if ($one_registration_per_email == true)
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'"; //else $sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_REGISTRATION'";
// get warning message from db
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGFORM_PROBLEM'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
?>
note : "register.php" requires two files so maybe the error is in one of them
settings.php :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "qazqazqaz1";
$db_name = "coco";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
db.php:
<?php
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "qazqazqaz1";
var $_DBname = "cocol";
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;
}
?>
I tried to solve it myself but I lost hope , so please tell me the accurate solution in steps .
thanks.
The error is referring to $obj->get. Basically you're executing the get method on a null variable, meaning it doesn't exist. After looking through all the code you have there, you aren't declaring $obj at any point.
I think you might need to check how you're passing in your settings to your Database object. For example:
$db = new database($db_server, ... , ...);
Updated:
You're hardcoding your connection anyway, just don't pass anything to the DB object.
Change this:
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
To this:
$db = new database();

Incorporate INSERT Mysql query for MVC controller in PHP

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.

php - class property not returning value

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.

Dynamically create a SQL statment from passed values in PHP

I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.

Connect to MySQL database using PHP OOP concept

I'm writing a class and handful of functions to connect to the database and retrieve the information from the tables. I went through previous posts having similar titles, but most of them have written using mysql functions and I am using mysqli functions.
I want somebody who can go through this simple script and let me know where I am making my mistake.
This is my class.connect.php:
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
This is my index.php:
<?php
require_once ("class.connect.php");
$connection = new mySQL();
$connection->connect('localhost', 'myDB', 'joker', 'names_list');
$myquery = "SELECT * FROM list";
$query = $connection->query($myquery);
while($array = $connection->fetch($query))
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
I am getting the error saying that Error querying the Database.
Few problems :-
you don't die without provide a proper mysql error (and is good practice to exit gracefully)
fetch method is only FETCH the first row
mysqli have OO method, why you still using procedural function?
The problem is either this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
or this:
while($array = $connection->fetch($query))
Because you are using the result from the query to query again. Basically, you are doing:
$r = mysqli_query($this->dbc, $sql);
$array = mysqli_fetch_array(mysqli_query($this->dbc, $r));
And you are getting an error, because $r is not a query string. When it's converted to a string, it's a "1" (from your other comment).
Try changing the function to (changed name of variable so you can see the difference):
public function fetch($result)
{
return mysqli_fetch_array($result);
}
or just call the function directly.
If you don't do your own db abstraction for learning php and mysql, you can use Medoo (http://medoo.in/).
It's a free and tiny db framework, that could save a huge work and time.
Obviously an error occurs on SELECT * FROM list you can use mysqli_error to find the error:
return mysqli_query($this->dbc, $sql) or die('Error:'.mysqli_error($this->dbc));
This will display the exact error message and will help you solve your problem.
Try to check this
https://pramodjn2.wordpress.com/
$database = new db();
$query = $database->select(‘user’);
$st = $database->result($query);
print_r($st);
class db {
public $server = ‘localhost';
public $user = ‘root';
public $passwd = ‘*****';
public $db_name = ‘DATABASE NAME';
public $dbCon;
public function __construct(){
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db_name);
}
public function __destruct(){
mysqli_close($this->dbCon);
}
/* insert function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
*/
public function insert($table,$values)
{
$sql = “INSERT INTO $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}else{
return false;
}
$this->dbCon->query($sql) or die(mysqli_error());
return mysqli_insert_id($this->dbCon);
}
/* update function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
$condition = array(‘id’ =>5,’first_name’ => ‘pramod!’);
*/
public function update($table,$values,$condition)
{
$sql=”update $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}
$k=0;
if(!empty($condition)){
foreach($condition as $key=>$val){
if($k==0){
$sql .= ” WHERE $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$result = $this->dbCon->query($sql) or die(mysqli_error());
return $result;
}
/* delete function table name, array value
$where = array(‘id’ =>5,’first_name’ => ‘pramod’);
*/
public function delete($table,$where)
{
$sql = “DELETE FROM $table “;
$k=0;
if(!empty($where)){
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$del = $result = $this->dbCon->query($sql) or die(mysqli_error());
if($del){
return true;
}else{
return false;
}
}
/* select function
$rows = array(‘id’,’first_name’,’last_name’);
$where = array(‘id’ =>5,’first_name’ => ‘pramod!’);
$order = array(‘id’ => ‘DESC’);
$limit = array(20,10);
*/
public function select($table, $rows = ‘*’, $where = null, $order = null, $limit = null)
{
if($rows != ‘*’){
$rows = implode(“,”,$rows);
}
$sql = ‘SELECT ‘.$rows.’ FROM ‘.$table;
if($where != null){
$k=0;
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}
if($order != null){
foreach($order as $key=>$val){
$sql .= ” ORDER BY $key “.htmlentities($val, ENT_QUOTES).””;
}
}
if($limit != null){
$limit = implode(“,”,$limit);
$sql .= ” LIMIT $limit”;
}
$result = $this->dbCon->query($sql);
return $result;
}
public function query($sql){
$result = $this->dbCon->query($sql);
return $result;
}
public function result($result){
$row = $result->fetch_array();
$result->close();
return $row;
}
public function row($result){
$row = $result->fetch_row();
$result->close();
return $row;
}
public function numrow($result){
$row = $result->num_rows;
$result->close();
return $row;
}
}
The mysqli_fetch_array function in your fetch method requires two parameters which are the SQL result and the kind of array you intend to return. In my case i use MYSQLI_ASSOC.
That is it should appear like this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql), MYSQLI_ASSOC);
return $array;
}
**classmysql.inc.php**
<?php
class dbclass {
var $CONN;
function dbclass() { //constructor
$conn = mysql_connect(SERVER_NAME,USER_NAME,PASSWORD);
//$conn = mysql_connect(localhost,root,"","");
if(!$conn)
{ $this->error("Connection attempt failed"); }
if(!mysql_select_db(DB_NAME,$conn))
{ $this->error("Database Selection failed"); }
$this->CONN = $conn;
return true;
}
//_____________close connection____________//
function close(){
$conn = $this->CONN ;
$close = mysql_close($conn);
if(!$close){
$this->error("Close Connection Failed"); }
return true;
}
function error($text) {
$no = mysql_errno();
$msg = mysql_error();
echo "<hr><font face=verdana size=2>";
echo "<b>Custom Message :</b> $text<br><br>";
echo "<b>Error Number :</b> $no<br><br>";
echo "<b>Error Message :</b> $msg<br><br>";
echo "<hr></font>";
exit;
}
//_____________select records___________________//
function select ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^select",$sql)){
echo "Wrong Query<hr>$sql<p>";
return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if((!$results) or empty($results)) { return false; }
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results)) {
$data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
//________insert record__________________//
function insert ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^insert",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if(!$results){
$this->error("Insert Operation Failed..<hr>$sql<hr>");
return false; }
$id = mysql_insert_id();
return $id;
}
//___________edit and modify record___________________//
function edit($sql="") {
if(empty($sql)) { return false; }
if(!eregi("^update",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
$rows = 0;
$rows = #mysql_affected_rows();
return $rows;
}
//____________generalize for all queries___________//
function sql_query($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
if(!eregi("^select",$sql)){return true; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
function extraqueries($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
}
?>
**config.inc.php**
<?php
ini_set("memory_limit","70000M");
ini_set('max_execution_time', 900);
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
############################################
# Database Server
############################################
if($_SERVER['HTTP_HOST']=="localhost")
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
else
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
#############################################
# File paths
#############################################
// For the Database file path
include("system/classmysql.inc.php");
//For the inc folders
define("INC","inc/");
//For the Function File of the pages folders
define("FUNC","func/");
//For the path of the system folder
define("SYSTEM","system/");
$table_prefix = 'dep_';
################################################################
# Database Class
################################################################
$obj_db = new dbclass();
?>
**Function Page**
<?php
// IF admin is not logged in
if(!isset($_SESSION['session_id']))
{
header("location:index.php");
}
$backpage = 'page.php?type=staff&';
if(isset($_REQUEST['endbtn']) && trim($_REQUEST['endbtn']) == "Back")
{
header("location:".$backpage);
die();
}
// INSERT into database.
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")
{
$pass = addslashes(trim($_REQUEST['password']));
$password = encrypt($pass, "deppro");
$username = addslashes(trim($_REQUEST['username']));
$sql = "select * from ".$table_prefix."users where `UserName` ='".$username."'";
$result = $obj_db->select($sql);
if(count($result) == 0)
{
$insert="INSERT INTO ".$table_prefix."users (`UserName`)VALUES ('".$username."')";
$sql=$obj_db->insert($insert);
$newuserid = mysql_insert_id($obj_db->CONN);
}
header("location:".$backpage."msg=send&alert=2");
die();
}
// DELETE record from database
if(isset($_REQUEST['action']) && trim($_REQUEST['action'])==3)
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
$sql_del = "Delete from ".$table_prefix."users where StaffID ='$id'";
$del = $obj_db->sql_query($sql_del);
header("location:".$backpage."msg=delete&alert=2");
die();
}
}
// UPDATE the record
$action=1;
if((isset($_REQUEST['action']) && trim($_REQUEST['action'])==2) && (!(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")))
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
//$id = $_SESSION['depadmin_id'];
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$title = stripslashes($row['StaffTitle']);
$action=2;
}
}
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Update")
{
$title = addslashes(trim($_REQUEST['title']));
$sql_upd ="UPDATE ".$table_prefix."users SET `StaffTitle` = '$title' WHERE StaffID ='$id'";
$result = $obj_db->sql_query($sql_upd);
$action=1;
header("location:".$backpage."msg=edited&alert=2");
die();
}
}
}
if(isset($_REQUEST['vid']) && trim($_REQUEST['vid']!=""))
{
$id = site_Decryption($_REQUEST['vid']);
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$username = stripslashes($row['UserName']);
}
}
}
?>
<td class="center"><span class="editbutton"> </span> <span class="deletebutton"> </span> <a class="lightbox" title="View" href="cpropertyview.php?script=view&vid=<?php echo site_Encryption($sql[$j]['PropertyID']); ?>&lightbox[width]=55p&lightbox[height]=60p"><span class="viewbutton"> </span></a></td>

Categories