Memory Leak or Connection not closed - php

I am having three files index.php, DB_Function, DB_Connect to connect through mysql server. But response is very slow and task is almost running according to the hosting server people.
index.php
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$uservalue= $user["userid"];
$usercal = $db->getUserByuserid($uservalue);
if ($usercal != false) {
$response["usercal"]["userid"] = $usercal["userid"];
$response["usercal"]["newcalorie"] = $usercal["newcalorie"];
$response["usercal"]["oldcalorie"] = $usercal["oldcalorie"];
$response["usercal"]["flag"] = $usercal["flag"];
$response["usercal"]["fat"] = $usercal["fat"];
$response["usercal"]["carbohydrate"] = $usercal["carbohydrate"];
$response["usercal"]["protein"] = $usercal["protein"];
$response["usercal"]["startdate"] = $usercal["startdate"];
$response["usercal"]["enddate"] = $usercal["enddate"];
$response["usercal"]["createddate"] = $usercal["createddate"];
$response["usercal"]["updateddate"] = $usercal["updateddate"];
$response["usercal"]["createdby"] = $usercal["createdby"];
$response["usercal"]["updatedby"] = $usercal["updatedby"];
}
$response["success"] = 1;
$response["user"]["userid"] = $user["userid"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["email"] = $user["email"];
$response["user"]["altemail"] = $user["altemail"];
$response["user"]["age"] = $user["age"];
$response["user"]["gender"] = $user["gender"];
$response["user"]["weight"] = $user["weight"];
$response["user"]["unit"] = $user["unit"];
$response["user"]["height"] = $user["height"];
$response["user"]["weightgoal"] = $user["weightgoal"];
$response["user"]["activitylevel"] = $user["activitylevel"];
$response["user"]["exerciselevel"] = $user["exerciselevel"];
$response["user"]["disease"] = $user["disease"];
$response["user"]["createddate"] = $user["createddate"];
$response["user"]["updateddate"] = $user["updateddate"];
$response["user"]["createdby"] = $user["createdby"];
$response["user"]["updatedby"] = $user["updatedby"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
else {
echo "Access Denied";
}
?>
DB_Function.php
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM userDetails WHERE email = '$email' AND password = '$password'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
// user not found
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByuserid($uservalue) {
$result = mysql_query("SELECT * FROM CalorieInfo WHERE userid= '$uservalue' ") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
$calresult = mysql_query("INSERT INTO CalorieInfo( userid,startdate, createddate, updateddate,createdby,updatedby) VALUES('$uservalue' ,NOW(), NOW(), NOW(),'$uservalue','$uservalue')");
if ($calresult) {
$id = mysql_insert_id();
$calresult = mysql_query("SELECT * FROM CalorieInfo WHERE id = $id");
return mysql_fetch_array($calresult);
}else{
// user not found
return false;
}
}
}
?>
DB_Connect.php
<?php
class DB_Connect {
// constructor
function __construct() {
//this->connect();
}
// destructor
function __destruct() {
//closing db
}
// Connecting to database
public function connect() {
require_once 'config.php';
// connecting to mysql
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
// selecting database
mysql_select_db(DB_DATABASE) or die(mysql_error());
// return database handler
return $con;
}
// Closing database connection
public function close() {
mysql_close();
}
}
?>
Is there anything more optimized that i should be aware of ?
Is something missing in my code. Hosting people says that tomcat and mysql is consuming more task.

Here are my recommendations
1.- Always close the connection after retrieving the data.
2.- If you are expecting just one row for a query like this
"SELECT * FROM userDetails WHERE email = '$email' AND password = '$password'
you should add LIMIT 1 at the end of the query for retrieving the only possible row
3.-Add indexes to the table
4.-Test your performance with mysqlslap

Related

Android Paginate JSON Data from PHP Mysql to App

The below PHP code gets all data from a MySQL DB and sends it to an android app. I want the data to be paginated.
ALL DATA PHP CODE
<?php
include 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$HostName;dbname=$DatabaseName", $HostUser, $HostPass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM `tiffa`");
$stmt->execute();
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($data);
} catch (PDOException $e) {
print "Connection failed! Please Try Again Or Contact Us: " . $e->getMessage() . "<br/>";
die();
$conn = null;
}
POJO/DATA MODEL CLASS
public class ImageList {
#SerializedName("image1name")
private String name;
#SerializedName("county")
private String county;
#SerializedName("image1URL")
private String imageurl;
#SerializedName("image2URL")
private String image2url;
public ImageList(String name,String county,String imageurl, String image2url) {
this.name = name;
this.county = county;
this.imageurl = imageurl;
this.image2url = image2url;
}
public String getName() {
return name;
}
String getCounty() {
return county;
}
String getImageurl() {
return imageurl;
}
String getImage2url() {
return image2url;
}
}
I have tried to pass the page_number and item_count (which come from the app) but I can't seem to get it. Here is my tried PHP Code. The POJO remains the same.
<?php
$page_number = $_GET['page_number'];
$item_count = $_GET['item_count'];
$from = $page_number * $item_count - ($item_count - 1);
$to = $page_number * $item_count;
$data = array();
include 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$HostName;dbname=$DatabaseName", $HostUser, $HostPass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM `tiffa`");
$stmt->execute();
if ($to > $stmt) {
array_push($response, array('status' => 'end'));
echo json_encode($response);
} else {
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($data);
}
array_push($response, array('images' => $images));
sleep(2);
echo json_encode($response);
catch (PDOException $e) {
print "Connection failed! Please Try Again Or Contact Us: " . $e->getMessage() . "<br/>";
die();
$conn = null;
}
Thanks for the leads #Nigel Ren. I resolved this by
<?php
$page_number = $_GET['page_no'];
$item_count = $_GET['item_cnt'];
$from = $page_number*$item_count - ($item_count-1);
$to = $page_number*$item_count;
$response=array();
$stats=array();
include 'dbconfig.php';
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
$total = mysqli_num_rows(mysqli_query($conn, "SELECT id from db1"));
if($to>$total)
{
array_push($response,array('status'=>'end'));
echo json_encode($response);
}
else
{
array_push($response,array('status'=>'ok'));
$count = $from;
$images = array();
$start = ($page - 1) * $limit;
//SQL query to fetch data of a range
$sql = "SELECT * from db1 limit $start, $item_count";
//Getting result
$result = mysqli_query($conn,$sql);
//Adding results to an array
$res = array();
while($row = mysqli_fetch_array($result))
{
$image122 = $row['image122'];
$image_path = $image122;
array_push($images,array('id'=>$count,'image_path'=>$image_path));
$count = $count+1;
}
array_push($response,array('images'=>$images));
sleep(2);
echo json_encode($response);
}
?>

Returning JSON message in PHP

I have written a PHP script to connect to a MySQL database and extract some information. I know that the majority of the script is working as it actually inserts a MAC address into the table (which is what it should do when the value of the MAC address in the DB table is NULL).
However, the resulting message from my script is "No license found (3)".
My question is, how can it be returning this message if it's inserting a MAC address? The else statement would only be entered if if (mysqli_num_rows($result) > 0) returned false.
What I want is for the MAC address to be checked (or inserted if NULL in the DB) and to return the message "Licensed".
Apologies for the nested if/else statements.
<?php
// Array for JSON response.
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
// Check for GET data.
if (isset($_GET["LicenseKey"])
&& isset($_GET["SoftwareId"])
&& isset($_GET["MacAddress"])) {
$licenseKey = $_GET['LicenseKey'];
$softwareId = $_GET['SoftwareId'];
$macAddress = $_GET['MacAddress'];
// Import database connection variables.
require_once __DIR__ . '/get_license_SQL.php';
$query = SQL_GET_LICENSE;
$query = str_replace("%1", $softwareId, $query);
$query = str_replace("%2", $licenseKey, $query);
$result = mysqli_query($db->connect(), $query);
if (!empty($result)) {
// Check for empty result.
if (mysqli_num_rows($result) > 0) {
// Get the result.
$result = mysqli_fetch_array($result);
$license = array();
$license["ExpiryDate"] = $result["ExpiryDate"];
// Check if MAC address exists.
$query = SQL_GET_MAC_ADDRESS;
$query = str_replace("%1", $licenseKey, $query);
$result = mysqli_query($db->connect(), $query);
if (!empty($result)) {
$result = mysqli_fetch_array($result);
echo json_encode($result);
if ($result["MacAddress"] == $macAddress
|| $result["MacAddress"] == NULL) {
// Device MAC address matches MAC address on record.
$response["success"] = 1;
$response["license"] = array();
if ($result["MacAddress"] == NULL) {
// Insert new MAC address into the database.
$query = SQL_INSERT_MAC_ADDRESS;
$query = str_replace("%1", $macAddress, $query);
$query = str_replace("%2", $licenseKey, $query);
mysqli_query($db->connect(), $query);
}
// Add MAC address to license array.
$license["MacAddress"] = $result["MacAddress"];
$response["message"] = "Licensed";
array_push($response["license"], $license);
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "License has already been used by another device";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No license found (2)";
array_push($response["license"], $license);
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No license found (3)";
array_push($response["license"], $license);
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No license found (4)";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) missing";
echo json_encode($response);
}
?>
db_connect.php :
<?php
class DB_CONNECT {
function __construct() {
$this->connect();
}
function connect() {
require_once __DIR__ . '/db_config.php';
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);
$db = mysqli_select_db($con, DB_DATABASE) or die(mysqli_error()) or die(mysqli_error());
return $con;
}
}
?>
get_license_SQL.php :
<?php
define('SQL_GET_LICENSE', "SELECT licenses.ExpiryDate
FROM licenses
WHERE licenses.SoftwareId=%1 AND licenses.LicenseKey=%2");
define('SQL_GET_MAC_ADDRESS', "SELECT licenses.MacAddress
FROM licenses
WHERE licenses.LicenseKey=%1");
define('SQL_INSERT_MAC_ADDRESS', "UPDATE licenses
SET MacAddress=%1
WHERE licenses.LicenseKey=%2");
?>
Please look at the following lines of code
if ($result["MacAddress"] == NULL) {
// Insert new MAC address into the database.
$query = SQL_INSERT_MAC_ADDRESS;
$query = str_replace("%1", $macAddress, $query);
$query = str_replace("%2", $licenseKey, $query);
mysqli_query($db->connect(), $query);
}
// Add MAC address to license array.
$license["MacAddress"] = $result["MacAddress"];
You are running the following query but you are not storing the result in a variable after insertion in the database:
mysqli_query($db->connect(), $query);
In the following line the $result array has the old values from the database which were fetched prior to insertion. Please try to store the values in a variable and use that variable after the insertion.
$license["MacAddress"] = $result["MacAddress"];

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.

Different authentication for different classes using Restler

I'm trying to build a REST api(using Restler) which takes in username and password for login and generates a session key. Once sessionkey is generated, user will be able to pass this session key to access other classes in the api. Is it possible to get the name of the class that invokes __isAuthenticated function?
My Auth Class:
<?php
class Auth implements iAuthenticate
{
public static $sessionKey;
public static $currentUser;
public $tempsesskey;
function __isAuthenticated ()
{
if (isset($_GET['useremail']) && isset($_GET['userpass'])) {
$user = $_GET['useremail'];
$pass = $_GET['userpass'];
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
mysql_query(
"UPDATE `userdetail` SET lastlogin=NOW()
WHERE useremail='$user' AND userpass=md5('$pass')");
if (mysql_affected_rows() > 0) {
$result = mysql_query(
"SELECT sessionkey from usersession where TIMESTAMPDIFF(MINUTE,lastactivity,now()) < 20 and useremail='$user'");
while ($row = mysql_fetch_assoc($result)) {
$tempsesskey = $row['sessionkey'];
}
if (strlen($tempsesskey) > 0) {
mysql_query(
"UPDATE usersession set lastactivity=now() where sessionkey='$tempsesskey'");
} else {
$tempsesskey = generateKey(52);
mysql_query(
"UPDATE `usersession` set sessionkey='$tempsesskey',keyvalid='Y' where useremail='$user'");
}
self::$currentUser = $user;
self::$sessionKey = $tempsesskey;
return TRUE;
}
} else
if (isset($_GET['sessionkey'])) {
$sesskey = $_GET['sessionkey'];
$sesskey = mysql_real_escape_string($sesskey);
$result = mysql_query(
"SELECT sessionkey from usersession where sessionkey='$sesskey' and TIMESTAMPDIFF(MINUTE,lastactivity,now()) < 20");
if (mysql_affected_rows() > 0) {
while ($row = mysql_fetch_assoc($result)) {
$tempsesskey = $row['sessionkey'];
self::$sessionKey = $tempsesskey;
}
return TRUE;
}
}
}
}
There is a simple way of setting the property on the Authentication class by adding custom php doc comment /annotation which is explained in Authentication with ACL. You can use the same technique for your purpose as well

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