Is this mysqli wrapper secure against SQL injection? - php

Here is how a wrapper looks like:
<?php
Class mysqliwrapper{
protected $_mysqli;
protected $_debug;
public function __construct($host, $username, $password, $database, $debug) {
$this->_mysqli = new mysqli($host, $username, $password, $database);
$this->_debug = (bool) $debug;
if (mysqli_connect_errno()) {
if ($this->_debug) {
echo mysqli_connect_error();
debug_print_backtrace();
}
return false;
}
return true;
}
public function q($query) {
if ($query = $this->_mysqli->prepare($query)) {
if (func_num_args() > 1) {
$x = func_get_args();
$args = array_merge(array(func_get_arg(1)),
array_slice($x, 2));
$args_ref = array();
foreach($args as $k => &$arg) {
$args_ref[$k] = &$arg;
}
call_user_func_array(array($query, 'bind_param'), $args_ref);
}
$query->execute();
if ($query->errno) {
if ($this->_debug) {
echo mysqli_error($this->_mysqli);
debug_print_backtrace();
}
return false;
}
if ($query->affected_rows > -1) {
return $query->affected_rows;
}
$params = array();
$meta = $query->result_metadata();
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($query, 'bind_result'), $params);
$result = array();
while ($query->fetch()) {
$r = array();
foreach ($row as $key => $val) {
$r[$key] = $val;
}
$result[] = $r;
}
$query->close();
return $result;
} else {
if ($this->_debug) {
echo $this->_mysqli->error;
debug_print_backtrace();
}
return false;
}
}
public function handle() {
return $this->_mysqli;
}
}
?>
This works fine:
$w = new mysqliwrapper("localhost","root","","testdb",1);
$r = $w->q("SELECT * FROM `testdb_news` WHERE `id`=? AND `lang`=?","is",16,'en');
However, this does not:
$r = $w->q("INSERT INTO `testdb_news` ('lang','title','content','date') VALUES (?,?,?,?)","ssss","en","NewTitle","NewContent",mktime());
Why? Should I be using ?-s only for SELECT statements? And go for insert like this?
$r = $w->q("INSERT INTO `testdb_news` (lang,title,content,date) VALUES ('en','newTitle','newContent','".mktime()."')");
Is this secure? Is this class actually secure? Thanks!

safe against injections. see this question which has similar questions Parameterized Query

Related

Insert MySql data from array [duplicate]

This question already has an answer here:
Mysqli prepared statements build INSERT query dynamically from array
(1 answer)
Closed 6 months ago.
<?php
$files=array(name1,name2,name3,);
$conn = new mysqli($host, $user, $pass, $name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO parmi_files (name)
VALUES ('$files')"; ///// -problem is here
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I want to insert each value from array to MySql row, please solve it out.
Iterate through the items in the array and add them individually:
foreach ($arrayWithValues as $key=>$value) {
$sql = "INSERT INTO parmi_files (name) VALUES ('$value')";
mysqli_query($conn, $sql);
}
Something like this to insert multiple records at once:
$files = array('name1', 'name2', 'name3');
// ...
$filesMap = implode(',', array_map(function($value) {
return "('" . $conn->real_escape_string($value) . "')";
}, $files));
$sql = "INSERT INTO parmi_files (name) VALUES $filesMap";
You could use a PDO abstraction layer for this
I have made a class for this in the past
It uses: PDO, bound parameters, prepared statements
and it inserts everything in one sql query and the insert looks like this:
$db->insertRows('test_table', $default_row, $rows);
The full code
(which might seem a bit long, but makes sense if you read it) including the code for the connection would look like:
<?php
// Establish connection (on demand)
$db = new PdoHelper(function(){
$db_server = 'localhost';
$db_port= '3306';
$db_name = 'your_database';
$db_user = 'your_username';
$db_pass = 'your_password';
$dsn = 'mysql:host='.$db_server.';dbname='.$db_name.';port='.$db_port;
$driver_options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);
$dbh = new PDO( $dsn, $db_user, $db_pass, $driver_options );
return $dbh;
});
// Make a blank sample to have default values for row keys
$default_row = array(
'a'=>null,
'b'=>null,
'c'=>null,
);
// The rows that we want to insert, with columns in the wrong order and nonsense
$rows = array(
array(
'b'=>'a2',
'c'=>'a3',
),
array(
'c'=>'b3',
'b'=>'b2',
),
array(
'b'=>'c2',
'c'=>'c3',
'nonsense'=>'boo',
),
);
// The actual insert query
// INSERT INTO `test_table` (`a`,`b`,`c`) VALUES (null,'a2','a3'), (null,'b2','b3'), (null,'c2','c3')
$db->insertRows('test_table', $default_row, $rows);
// The class that does it all
class PdoHelper {
private $db, $factory;
public function __construct($factory)
{
$this->factory = $factory;
}
public function connect()
{
$cb = $this->factory;
$this->db = $cb();
}
public function release()
{
$this->db = null;
}
public function implyConnect()
{
if(!$this->db){
$this->connect();
}
}
public function begin()
{
$this->implyConnect();
if($this->db instanceof PDO){
$this->db->beginTransaction();
}
}
public function commit()
{
$this->implyConnect();
if($this->db instanceof PDO){
$this->db->commit();
}
}
public function prepare($sql, $data=null, $callback=null)
{
$err = null;
$flat_data = array();
if($data){
$flat_data = self::flatten($data);
$sql = preg_replace_callback('/\?/isu', function($v) use (&$data) {
$val = array_shift($data);
if(is_array($val)){
return self::arrayToPlaceholder($val);
}
return '?';
}, $sql);
}
$this->implyConnect();
if($this->db instanceof PDO){
$stmt = $this->db->prepare($sql);
if($stmt instanceof PDOStatement){
$i = 1;
foreach($flat_data as $v) {
if(is_int($v)){
// workaround for a PDO bug with LIMIT ?,?
$stmt->bindValue($i++, $v, PDO::PARAM_INT);
}else{
$stmt->bindValue($i++, $v, PDO::PARAM_STR);
}
}
}
}
if($callback){
return call_user_func_array($callback, array($stmt));
}
return $stmt;
}
public function query($sql)
{
$res = false;
$args = func_get_args();
$data = array();
$callback = null;
if(isset($args[2])){
$data = $args[1];
$callback = $args[2];
}else
if(isset($args[1])){
if(is_callable($args[1])){
$callback = $args[1];
}else{
$data = $args[1];
}
}
$this->implyConnect();
$stmt = $this->prepare($sql, $data);
$res = $stmt->execute();
if($res && $callback && is_callable($callback)){
return call_user_func_array($callback, array($stmt, $this->db));
}
return $stmt;
}
// Helper functions
public function insertRows($table, $default, $rows=array(), $flag=null, $chunk_size=500)
{
if(empty($rows)){
return null;
}
$chunks = array_chunk($rows, $chunk_size);
foreach($chunks as $rows){
$data = array();
$data[] = $this->extend($default, $rows);
// http://stackoverflow.com/questions/1542627/escaping-column-names-in-pdo-statements
$flag = strtolower($flag);
$flags = array(
'ignore'=>'INSERT IGNORE INTO ',
'replace'=>'REPLACE INTO ',
);
$cols = array();
foreach($default as $k=>$v){
$k = str_replace('`', '``', $k);
$cols[] = '`'.$k.'`';
}
$sql = (isset($flags[$flag])?$flags[$flag]:'INSERT INTO ').$table.' ('.implode(',', $cols).') VALUES ?';
if($flag==='update'){
$cols = array();
foreach($default as $k=>$v){
$k = str_replace('`', '``', $k);
$cols[] = '`'.$k.'`=VALUE('.$k.')';
}
$sql .= ' ON DUPLICATE KEY UPDATE '.implode(', ', $cols);
}
$res = $this->query($sql, $data);
if(!$res){
return $res;
}
}
return $res;
}
public function insertRow($table, $default, $row, $flag=null)
{
$rows = array($row);
return $this->insertRows($table, $default, $rows, $flag);
}
// Helper functions
public static function extend($set, $rows)
{
foreach($rows as $k=>$v){
$v = array_intersect_key($v, $set);
$rows[$k] = array_replace($set, $v);
}
return $rows;
}
public static function flatten($x)
{
$d = array();
if(is_array($x)){
foreach($x as $k=>$v){
$d = array_merge($d, self::flatten($v));
}
}else{
$d[] = $x;
}
return $d;
}
public static function arrayToPlaceholder($array, $timeZone=null) {
return implode(',', array_map(function($v) use($timeZone){
if(is_array($v)){
return '('.self::arrayToPlaceholder($v, $timeZone).')';
}
return '?';
}, $array));
}
public function arrayToList($array, $timeZone=null) {
return implode(',',array_map(function($v) use($timeZone){
if(is_array($v)){
return '('.self::arrayToList($v, $timeZone).')';
}
$this->implyConnect();
return $this->escape($v);
},$array));
}
public function escape($val, $stringifyObjects=false, $timeZone=false) {
if(is_null($val)) return 'NULL';
if(is_bool($val)) return ($val) ? 'true' : 'false';
if(is_int($val)) return (string)$val;
if(is_float($val)) return (string)$val;
if (is_array($val)) {
return $this->arrayToList($val, $timeZone);
}
if(is_callable($val)){ return null; } // TODO
$val = preg_replace_callback('/[\0\n\r\b\t\\\'\"\x1a]/um', function($s) {
switch($s) {
case "\0": return "\\0";
case "\n": return "\\n";
case "\r": return "\\r";
case "\b": return "\\b";
case "\t": return "\\t";
case "\x1a": return "\\Z";
default: return "\\".$s;
}
}, $val);
return $this->db->Quote($val);
}
// Debug functions
public function getSQL($sql, $data){
foreach($data as $k=>$v){
if(is_array($v)){
$data[$k] = self::arrayToList($v);
}else{
$this->implyConnect();
$data[$k] = $this->escape($v);
}
}
$sql = preg_replace_callback('/\?/', function($match) use(&$data)
{
return array_shift($data);
}, $sql);
return $sql;
}
}

class which generates all queries in php

I'm creating a class in which MySQL queries will be generated automatically , but I've some problem ...
here is my Database class...
<?php
class Database {
var $host="localhost";
var $username="";
Var $password="";
var $database="";
var $fr_query;
var $row= array() ;
public function connect()
{
$conn= mysql_connect($this->host,$this->username,$this->password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
}
public function db()
{
$conn_db = mysql_select_db($this->database);
if(! $conn_db )
{
echo 'Could Not Connect the Database';
}
}
public function run_query($sql)
{
$run = mysql_query($sql);
if(!$run)
{
throw new Exception("!!!!!Invalid query!!!!!!!");
}
$newId = mysql_insert_id();
if($newId)
{
return $newId;
}
return true;
}
public function fetchRow($fr)
{
if($fr)
{
$run = mysql_query($fr);
if($run)
{
return mysql_fetch_assoc($run);
}
}
return null;
}
function fetchAll($fr_query)
{
if($fr_query)
{
$run = mysql_query($fr_query);
if($run)
{
$data=array();
while($row=mysql_fetch_assoc($run))
{
$data[]=$row;
}
return $data;
}
}
return null;
}
}
$n = new Database();
$n->connect();
$n->db();
?>
and this is my test.php
<?php
include("database.php");
class Model_Abstract
{
protected $_data = array();
protected $_tableName = null;
protected $_primaryKey = null;
public function getTableName()
{
return $this->_tableName;
}
public function getPrimaryKey()
{
return $this->_primaryKey;
}
public function __set($key, $value = NULL)
{
$key = trim($key);
if(!$key)
{
throw new Exception('"$key" should not be empty.');
}
$this->_data[$key] = $value;
return $this;
}
public function __get($key)
{
$key = trim($key);
if(!$key)
{
throw new Exception('"$key" should not be empty.');
}
if(array_key_exists($key, $this->_data))
{
return $this->_data[$key];
}
return NULL;
}
public function insert()
{
print_r($this->_data);
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", array_keys($this->_data))."'";
echo $query = "INSERT INTO `{$this->getTableName()}` ({$keyString}) VALUES ({$valueString})";
$this->adpater()->run_query($query);
echo 'Inserted';
}
public function setData($data)
{
if(!is_array($data))
{
throw new Exception('"$data" should not be empty.');
}
$this->_data = $data;
return $this;
}
public function load($id, $key = null)
{
if(!is_int($id) && $id)
{
throw new Exception('"$id" should not be blank.');
}
if($id)
{
echo $query = "SELECT * FROM `{$this->getTableName()}` WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$data[] = $this->adpater()->fetchRow($query);
$tabelName = $this->getTableName();
foreach($data as &$_data)
{
print_r($_data);
$object = new $tabelName();
$object->setData($_data);
$_data = $object;
}
print_r($data);
return $this;
/*
$query = "SELECT * FROM `{$this->getTableName()}` WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$this->_data = $this->adpater()->fetchRow($query);
return $this; */
}
}
public function loadAll()
{
$query = "SELECT * FROM `{$this->getTableName()}`";
$data[] = $this->adpater()->fetchAll($query);
return $data;
}
public function delete($id, $key = null)
{
if(!is_int($id) && $id)
{
throw new Exception('"$id" should not be blank.');
}
if($id)
{
echo $query = "DELETE FROM `{$this->getTableName()}` WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$data[] = $this->adpater()->run_query($query);
$tabelName = $this->getTableName();
$msg = 'Deleted Successfully....';
return $msg;
}
}
public function update()
{
print_r($this->_data);
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", array_keys($this->_data))."'";
echo $query = "UPDATE`{$this->getTableName()}` SET ({$keyString}) = ({$valueString}) WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$this->adpater()->run_query($query);
echo 'Updated';
}
public function adpater()
{
return new Database();
}
}
class Product extends Model_Abstract
{
protected $_tableName = 'product';
protected $_primaryKey = 'product_id';
}
$product = new Product();
echo $product->name;
$product->insert();
print_r($product);
$product = new Product();
$product->name = 'Nokia Lumia';
$product->description = 'Windows';
$product->price = '15000';
$product->quantity = '12';
$product->sku = 'x2';
$product->status = '2';
$product->created_date = '0000-00-00 00:00:00';
$product->updated_date = ' ';
?>
So in here my problem is in Insert query, the values are same the column_name ...
I'm having Problem in loadAll();
the browser says "Catchable fatal error: Object of class Product could not be converted to string in"
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", array_keys($this->_data))."'";
Same lines, same value. Perhaps you meant
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", $this->_data) ."'";
Which would take the array keys for $keyString and the array values for $valueString.
Depreciation warning
mysql_* are deprecated functions. Use mysqli_* or PDO
Warning
This class does not protect you against SQL injections.

Select and call_user_func_array issue

I've this function:
private function db_bind_array($stmt, &$row) {
$md = $stmt->result_metadata();
$param = array();
while($field = $md->fetch_field()) { $param[] = &$row[$field->name];}
return call_user_func_array(array($stmt, 'bind_result'), $param);
}
private function db_query($sql, $bind_param, $param) {
if($stmt = $this->conn->prepare($sql)) {
if(!$bindRet = call_user_func_array(array($stmt,'bind_param'),
array_merge(array($bind_param), $param))) $this->Terminate();
if(!$stmt->execute()) $this->Terminate();
$res = array();
if($this->db_bind_array($stmt, $res)) return array($stmt, $res);
}
}
protected function Select($recs, $table, $where, $bind_param, $param, $order_by = '', $sort = '', $limit = 1) {
if($order_by != '') $order_by = 'ORDER BY '.$order_by;
$sql = "SELECT $recs FROM $table WHERE $where $order_by $sort LIMIT $limit";
return $this->ExeSelect($sql, $bind_param, $param);
}
private function ExeSelect($sql, $bind_param, $param) {
if($res = $this->db_query($sql, $bind_param, array(&$param))) {
$stmt = $res[0]; $row = $res[1];
while($stmt->fetch()) {$this->row = $row; return $row;}
$stmt->close();
}
}
And I use it:
$row = $this->Select('id, name, title, 'Articles', where id >, 'i', 10, 'DESC', '', 10)
The problem is that it returns only one record instead of 10.
What's the problem?
Thanks
The problem is this line: while($stmt->fetch()) {$this->row = $row; return $row;}. You immediately return that result. Build an array before you return it.
private function ExeSelect($sql, $bind_param, $param) {
$ret = array();
if($res = $this->db_query($sql, $bind_param, array(&$param))) {
$stmt = $res[0]; $row = $res[1];
while($stmt->fetch()) {$ret[] = $row; }
$stmt->close();
}
return $ret;
}

What is wrong with my function?

I have reproduced this function:
function getTables()
{
global $db;
$value = array();
if (!($result = $db->query('SHOW TABLES'))) {
return false;
}
while ($row = $db->fetchrow($result)) {
if (empty($this->tables) or in_array($row[0], $this->tables)) {
$value[] = $row[0];
}
}
if (!sizeof($value)) {
$db->error("No tables found in database");
return false;
}
return $value;
}
in this manner:
public function getTables() {
$value = array();
$tables = array();
$sql = "SHOW TABLES";
if($stmt = $this->connect->prepare($sql)) {
$stmt->execute();
while( $row = $stmt->fetch_row() ) {
if(empty($tables) or in_array($row[0], $tables)) {
$value[0] = $row[0];
}
}
$stmt->close();
if(!sizeof($value)) {
echo 'The database has no tables';
}
return $value;
} else {
echo 'Couldn\t query the database';
}
}
But the second method returns me The database has no tables which is not true because I have one table in the db.
What is it wrong with the second method ?
In case you wonder what connect does :
public $connect;
public function __construct() {
// Define The Database Connection Or Die If Failed Connecting
$this->connect = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(DB_CONNECTION_ERROR_MESSAGE);
}
It make a connection with the database. And prepare() it's a mysqli statement. I tried with query() too, same result.
Correct code. Use query instead of prepare:
public function getTables()
{
$value = array();
$tables = array();
$sql = "SHOW TABLES";
if ($res = $this->connect->query($sql))
{
while ($row = $res->fetch_row())
{
if (empty($tables) or in_array($row[0], $tables))
{
$value[] = $row[0];
}
}
if (!sizeof($value))
{
echo 'The database has no tables';
}
return $value;
}
else
{
echo 'Could not query the database';
}
}
If you still want to use prepare then you will also need $stmt->bind_result and $stmt->fetch() instead of fetch_row.
I think this piece of code is broken
$value[] = $row[0];
and probably you should change it to
$value[0] = $row[0]; or array_push($value, $row[0])

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