I am trying to learn object oriented programming.
The problem what I have is how to add link under mysqli_query() inside the class.
In procedural style I just create a $variable with connection details and then using it inside the mysqli_query($variable, $sql) etc.
In my class I have function connect() which will connect to database and return true but Haw can I use it inside my mysqli_query() please? please see the code here:
<?php
class DB {
protected $db_name = 'OOP_forum';
protected $db_user = 'Marcel';
protected $db_pass = *****;
protected $db_host = 'localhost';
public function connect() {
$connection = mysqli_connect($this->db_host, $this->db_user, $this->db_pass);
mysqli_select_db($connection, $this->db_name);
return true;
}
public function processRowSet($rowSet, $singleRow = false) {
$resultArray = array();
while($row = mysqli_fetch_assoc($rowSet)) {
arraypush($resultArray, $row);
}
if($singleRow==true) {
return $resultArray[0];
}else {
return $resultArray; }
}
public function select ($table, $where, $column = '*') {
$sql = "SELECT $column FROM $table WHERE $where";
$result = mysqli_query($sql);
if(mysqli_num_row($result) == 1 ){
return $this->processRowSet($result, true);
} else
{ return $this->processsRowSet($result);
}
}
public function update ($data, $table, $where) {
foreach ($data as $column->$value) {
$sql = "UPDATE $table SET $column = $value WHERE $where";
mysqli_query($sql) or die(mysqli_error());
}
return true;
}
public function delete ($table, $column, $where) {
$sql = "DELETE FROM $table WHERE $column = $where";
if (query($sql)=== TRUE) {
echo "Record Deleted sucessfully";
}else {
echo "Error deleting record: " . $connection->error;
}
}
public function insert($data, $table) {
$columns = "";
$values = "";
foreach ($data as $column->$value) {
$columns .= ($columns == "") ? "": ", " ;
$columns .= $column;
$values .= ($values == "") ? "" : ", ";
$values .= $value;
}
$sql = "insert into $table ($columns) values ($values)";
mysqli_query($sql) or die(mysqli_error());
return mysqli_insert_id();
}
}
?>
Before trying to learn OOP programming you have to learn basic OOP syntax.
In order to do so forget for a while about creating your own classes and learn how to use already made ones. So, first of all learn how to use mysqli. Which is already a class.
Better yet, learn PDO instead, as, unlike mysqli, it's already a ready to use database access class, with it you don't need functions like processRowSet, for example.
Related
I have trouble understanding OOP...
Lets say I wanted to create a page that adds a new user to a database and wanted to work with classes.
For that scenario i'd create a form with a function.
There are forms for each CRUD functionality - renderHTMLFormAddUser() :
...
<form action="" method="POST" >;
<label>Shopname*</label><br>;
<input type="text" name="shopname" class="input_wide" required><br>;
<label>Username*</label><br>;
<input type="text" name="username" class="input_wide" required><br>;
<input type="submit" value="add" name="submit" >
...
a DataBaseConnector class:
class DataBaseConnector
{
protected $con;
public function __construct()
{
$this->con=mysqli_connect('mariaDB','root','123456','produktmuster');
}
public function getConnection()
{
return $this->con;
}
public function __destruct()
{
$this->con->close();
}
}
and a QueryDatabase class that requires the DataBaseConnector connection as a transfer parameter in its constructor:
class QueryDatabase
{
private $con;
public function __construct(DataBaseConnector $con)
{
$this->con = $con;
}
public function addUser($shopname,$username)
{
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
$result = mysqli_query($this->con->connect(), $sql);
return $result;
}
To get the $_POST values in the QueryDatabase add User function, i'd need to declare variables like so:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
But is there a better way to do so?
Like maybe renderHTMLFormAddUser()->'shopname'.
Im just trying to understand what is the cleanest way to code in this scenario.
Because using a function to render the forms the adduser.php would look something like this:
$createuserform=new Forms();
$createuserform->renderHTMLFormAddUser();
$shopname= $_POST['shopname']; // this is what confuses me, you'd have to look into the
$username= $_POST['username']; // renderHTMLFormAddUser() function to see the code
$db = new DataBaseConnector();
$query= new QueryDatabase();
$query->addUser($shopname,$username)
Should I just create an own page that posts the form to a page that then uses the data?
In the beginning i simply used no transfer parameters with the addUser function, and it started with declaring the $_POSTs:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
...
But I was told it was unsafe to do so - in that regard, I sanitize my data but for the sake of easier example i stripped away all the unnecessary code.
Should I take a completely different approach, just would like to know the cleanest way to add form input data into a database.
Well, there are many approaches to do this. You can also do my OOPs approach:
Make a define.php to set the constant variables & database connection variables:
define.php
define("DB_HOSTNAME", "localhost");
define("DB_USERNAME", "your_username");
define("DB_PASSWORD", "your_password");
define("DB_NAME", "your_databasename");
define("custom_variable", "custom_variable_value");
define("baseurl", "https://localhost/myproject/");
Then, make dbase.php, to create a dynamic SQL function:
You don't need to change this file. You just need to call this class. This file work as the core file of the system.
Dbase.php
<?php session_start();
date_default_timezone_set("Asia/Karachi");
require_once("define.php");
Class Dbase
{
private $Host = DB_HOSTNAME;
private $UserName = DB_USERNAME;
private $Password = DB_PASSWORD;
private $DBname = DB_NAME;
private $connDb = false;
public $LastQuery = null;
public $AffectedRows = 0;
public $InsertKey = array();
public $InsertValues = array();
public $UpdateSets = array();
public $id;
public function __construct()
{
$this->connect();
}
protected function connect()
{
$this->connDb = #mysqli_connect($this->Host, $this->UserName, $this->Password);
if (!($this->connDb)) {
die('Database Connection Failed.<br>' . mysql_error($this->connDb));
} else {
$Select = mysqli_select_db($this->connDb,$this->DBname);
if (!$Select) {
die('Database Selection Failed.<br>' . mysql_error($this->connDb));
}
}
mysqli_set_charset($this->connDb,'utf8');
}
public function close()
{
if (!mysqli_close($this->connDb)) {
die('Closing Connection Failed.<br>');
}
}
public function escape($value)
{
if (function_exists('mysql_real_escape_string')) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
} else {
if (!get_magic_quotes_gpc()) {
$value = addcslashes($value);
}
}
return $value;
}
public function query($sql)
{
$query = $sql;
$result = mysqli_query($this->connDb,$sql);
// $this->displayQuery($result);
return $result;
}
public function displayQuery($result)
{
if (!$result) {
$output = 'Database Query Failed' . mysql_error($this->connDb) . '<br>';
$output .= 'Last Query was' . $this->LastQuery;
die($output);
} else {
$this->AffectedRows = mysqli_affected_rows($this->connDb);
}
}
public function fetchAll($sql)
{
$result = $this->query($sql);
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[] = $row;
}
// mysql_free_result($result);
return $output;
}
public function fetchOne($sql)
{
$output = $this->fetchAll($sql);
return $output;
// return array_shift($output);
}
public function prepareInsert($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->InsertKey[] = $key;
$this->InsertValues[] = $this->escape($value);
}
}
}
public function insert($table = null)
{
if (!empty($table) && !empty($this->InsertKey) && !empty($this->InsertValues)) {
$sql = "insert into '{$table}' ('";
$sql .= implode("','", $this->InsertKey);
$sql .= "') values ('";
$sql .= implode("','", $this->InsertValues);
$sql .= "')";
if ($this->query($sql)) {
$this->id = $this->lastId();
return true;
}
return false;
} else {
return false;
}
}
public function prepareUpdate($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->UpdateSets[] = "`{$key}` = '" . $this->escape($value) . "'";
}
}
}
public function update($table = null, $id = null, $whereId)
{
if (!empty($table) && !empty($id) && !empty($this->UpdateSets)) {
$sql = "update `{$table}` set";
$sql .= implode(",", $this->UpdateSets);
// $sql.="where id='".$this->escape($id)."'";
$sql .= "where '" . $whereId . "'='" . $this->escape($id) . "'";
return $this->query($sql);
} else {
return false;
}
}
public function lastId()
{
return mysqli_insert_id($this->connDb);
}
public function TotalNumberOfRecords($sql)
{
$result = $this->query($sql);
$output = mysqli_num_rows($result);
return $output;
}
public function GetServerInfo()
{
return mysqli_get_server_info();
}
}
Create a Query.php file. This file work as your model file as in MVC.
Query.php
<?php include "Dbase.php";
Class Query extends Dbase
{
public function __construct()
{
$this->connect();
date_default_timezone_set("Asia/Karachi");
}
public function getData($idlevelOne)
{
$sql = "SELECT * FROM `table` where level_one_id=$idlevelOne ORDER BY `sorting` ASC";
$result = $this->fetchAll($sql);
return $result;
}
/*For Insert & Edit, use this fucntion*/
public function editMember($email, $phone, $address, $city, $country, $zipcode, $id)
{
$sql = "UPDATE `members` SET `email` = '" . $email . "', `phone` = '" . $phone . "', `address` = '" . $address . "'
, `city` = '" . $city . "', `country` = '" . $country . "', `zip_code` = '" . $zipcode . "'
WHERE `id` = '$id'";
$result = $this->query($sql);
return $result;
}
}
Now, you just need to call the Query class in your PHP files to get the data.
<?php
include "Query.php";
$ObjQuery = new Query();
$ObjQuery->getData(1);
I have a HTML form which has more than 25 entries.
I know how to insert normal form data into MySQL database using PHP PDO. But I just want to know if there is any alternative way in which I can store the form entries to an array and insert the data into database using the array.
Because writing an insert statement for more than 25 columns is cumbersome.
You could always use a PDO wrapper class, I use the class below to handle most of my PDO queries:
class DB {
protected
// Return from mysql statement
$data = array(),
// Used for checking whether something was added to the JSON object and remove it if the table column doens't exist
$table_cols = array(),
// Storing the table name we are working with
$table = '';
protected static
// PDO connection to the DB
$_conn = null,
// The DB credentials retrieved from the ini file
$_credentials = array ();
private
$_id = -1,
$_keys = array(),
$_values = array(),
$_last_insert_id = -1,
$_results = array();
//
// PUBLIC FUNCTIONS
//
public function __construct () {
if (self::$_conn === null) {
self::setCredentials();
try {
self::$_conn = new \PDO("mysql:host=" . self::$_credentials['host'] . ";dbname=" . self::$_credentials['dbname'] , self::$_credentials['username'], self::$_credentials['password']);
} catch (\PDOException $e) {
DebugLog::instance('DB')->error($e, 'db_connection');
}
}
}
public function insert ($data) {
$data = $this->checkCols($data);
// Allows us to quickly clone data by removing the id and inserting as a new record
if (isset($data['id'])) {
unset($data['id']);
}
$this->data = $data;
$this->setDataBinding();
$sql = "INSERT INTO `" . self::$_credentials['dbname'] . "`.`{$this->table}` (`" . implode('`, `', $this->_keys) . "`) VALUES (:" . implode(', :', $this->_keys) . ");";
return $this->prepareAndExecute($sql);
}
public function update ($data) {
$data = $this->checkCols($data);
if (!isset($data['id'])) {
// Houston we have a problem, there needs to be an id to update a record
DebugLog::instance('DB')->error("No ID set for Update: " . implode(', ', array_keys($data)), 'db_id_' . $this->table);
} else {
// We need to unset the id because it shouldn't be in the data binding
// But we still hold onto it for the where clause
$id = $data['id'];
unset($data['id']);
$this->data = $data;
$this->setDataBinding();
$sql = "UPDATE `" . self::$_credentials['dbname'] . "`.`{$this->table}` SET ";
$query_string = "";
foreach ($this->_keys as $i => $key) {
$query_string .= "`{$key}` = :{$key}, ";
}
$query_string = trim($query_string);
if (substr($query_string, -1) === ',') {
$query_string = substr($query_string, 0, -1);
}
$sql .= $query_string . " WHERE `id` = '{$id}'";
return $this->prepareAndExecute($sql);
}
return false;
}
public function remove ($id) {
$this->rawQuery("DELETE FROM `{$this->table}` WHERE `id` = '{$id}';");
}
public function rawQuery ($sql) {
try {
$pdo = self::$_conn->query($sql);
$pdo->setFetchMode(\PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
DebugLog::instance('DB')->error($e, 'db_query_' . $this->table);
return array();
}
return $pdo->fetchAll();
}
//
// GETTERS
//
public function getColumns () {
return $this->table_cols;
}
public function getLastInsertID () {
return $this->_last_insert_id;
}
public function getRecord ($id) {
$this->_id = $id;
$response = $this->rawQuery("SELECT * FROM `{$this->table}` WHERE `id` = '{$id}'");
$this->_results = $response[0];
}
public function getResults () {
return $this->_results;
}
public function close () {
$this->setDefaults();
}
//
// PROTECTED FUNCTIONS
//
protected function initColumns () {
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . self::$_credentials['dbname'] . "' AND TABLE_NAME = '{$this->table}';";
$response = $this->rawQuery($sql);
if (!empty($response)) {
return $this->parseColumns($response);
}
return array();
}
//
// PRIVATE FUNCTIONS
//
private function setDataBinding () {
$this->_keys = array_keys($this->data);
foreach ($this->data as $k => $v) {
$this->_values[':' . $k] = $v;
}
}
private function prepareAndExecute ($sql) {
try {
$q = self::$_conn->prepare($sql);
$q->setFetchMode(\PDO::FETCH_ASSOC);
if ($q->execute($this->_values)) {
while ($r = $q->fetch()) {
$this->_results[] = $r;
}
$this->_last_insert_id = self::$_conn->lastInsertId();
return true;
} else {
DebugLog::instance('DB')->error('Failed to execute', 'db_' . $this->table);
}
} catch (\PDOException $e) {
DebugLog::instance('DB')->error($e, 'db_' . $this->table);
}
return false;
}
private function checkCols ($array) {
foreach ($array as $col => $val) {
if (!in_array($col, $this->table_cols)) {
unset($array[$col]);
}
}
return $array;
}
private static function setCredentials () {
// I actually use a config file here, instead of hard coding
self::$_credentials = array(
'host' => '',
'dbname' => '',
'username' => '',
'password' => ''
);
}
private function parseColumns ($cols) {
$array = array();
foreach ($cols as $index => $col_array) {
$array[] = $col_array['COLUMN_NAME'];
}
return $array;
}
private function setDefaults () {
$this->data = array();
$this->table_cols = array();
$this->table = '';
self::$_conn = null;
$this->_keys = array();
$this->_values = array();
$this->_last_insert_id = -1;
$this->_results = array();
}
}
Then for each table, create a class that extends the class above. For example, lets say we have a users table:
class UsersTable extends DB {
public function __construct () {
// Parent constructor creates the DB connection
parent::__construct();
// Now let's set the desired table based on this class
$this->table = "users";
// Set the table columns, for mysql column validation
$this->table_cols = $this->initColumns();
}
}
Usage is than as simple as:
$table = new UsersTable();
$table->insert($record);
As long as your array has the 25 values in the same order as the table you can use unnamed parameters and lazy binding See PDO info
$sql ="INSERT INTO table_name VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)";
$stmt = $dbh->prepare($sql);
$stmt->execute($array);
i'm just switching from mysql_* to PDO since i read that mysql_* will be removed in the future and now i have no idea to abstract my current class for insert,update,and delete operation to PDO, maybe some one can point me out how to translate it to PDO based?
this is my connection class for handling all connection and other related function (i already making this one PDO so there is no problem with this)
<?php
require_once(folder.ds."constants.php");
class MySQLDatabase {
private $dbh;
private $host = DB_SERVER;
private $dbname = DB_NAME;
private $stmt;
public $query_terakhir;
public $error_text;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try{
$this->dbh = new PDO($dsn,DB_USER,DB_PASS,$options);
}
catch(PDOException $e) {
date_default_timezone_set('Asia/Jakarta');
$dt = time();
$waktu = strftime("%Y-%m-%d %H:%M:%S", $dt);
$log = array_shift(debug_backtrace());
file_put_contents('PDOErrors.txt',$waktu. ": " .$e->getMessage(). ": " .$log['file']. ": line " .$log['line']. "\n", FILE_APPEND);
}
}
public function query($sql){
$this->stmt = $this->dbh->prepare($sql);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function fetchall(){
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function fetch(){
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
}
$database = new MySQLDatabase();
?>
and here is one of my class that help me to do saving(create or update), delete and others, with this class i only need to change $nama_tabel for table name, $db_fields for my table fields and public $xxxxx that match with my table fields and create, update and delete function can work perfectly...
but with pdo i just can't figure out how to make it work for create, update and delete with the same method as above....
<?php
require_once('database.php');
class staff{
public static $nama_tabel="staff";
protected static $db_fields = array('id','name','job');
public $id;
public $name;
public $job;
private function has_attribute($attribute){
$object_var = $this->attributes();
return array_key_exists($attribute,$object_var);
}
protected function attributes(){
$attributes = array();
foreach(self::$db_fields as $field){
if(property_exists($this, $field)){
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes(){
global $database;
$clean_attributes = array();
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public function create(){
global $database;
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO " .self::$nama_tabel." (" ;
$sql .= join(", ", array_keys($attributes));
$sql .=")VALUES('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)){
$this->id_kategori = $database->insert_id();
return true;
}else{
return false;
}
}
public function update(){
global $database;
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value){
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql ="UPDATE " .self::$nama_tabel." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .=" WHERE id=" . $database->escape_value($this->id);
$database->query($sql);
return($database->affected_rows() == 1) ? true : false;
}
public function delete(){
global $database;
$sql = "DELETE FROM " .self::$nama_tabel;
$sql .= " WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
if(!empty($this->gambar)){
$target = website .ds. $this->upload_dir .ds. $this->gambar;
unlink($target);
}
return($database->affected_rows() == 1) ? true : false;
}
}
?>
updated: this is my approach for create function after tweaking from update function from GolezTrol, but not inserting the value instead it inserting name=:name and content=:content and so on
Updated:its already fixed! here is the right one
public function create(){
global $database;
$attributes = $this->attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value){
$attribute_pairs[] = ":{$key}";
}
$sql = "INSERT INTO " .self::$nama_tabel." (" ;
$sql .= join(", ", array_keys($attributes));
$sql .=")VALUES(";
$sql .= join(", ", $attribute_pairs);
$sql .= ")";
$database->query($sql);
foreach($attributes as $key => $value){
$database->bind(":$key", $value);
}
if($database->execute()){
$this->id = $database->lastInsertId();
return true;
}else{
return false;
}
}
2nd update : i experiencing some weird thing in while loop operation where i doing while and inside the while i check if this field id is equal with my other table id then i will show that id name field... and it show, but stoping my while loop, so i only get 1 row while loop (it supposed to show 40 row)
$database->query($sql_tampil);
$database->execute();
while($row = $database->fetch()){
$output = "<tr>";
if(!empty($row['id']))
$output .="<td><a data-toggle=\"tooltip\" data-placement=\"top\"
title=\"Tekan untuk mengubah informasi kegiatan ini\"
href=\"ubah_cuprimer.php?cu={$row['id']}\"
>{$row['id']}</a></td>";
else
$output .="<td>-</td>";
if(!empty($row['name'])){
$y = "";
$x = $row['name'];
if(strlen($x)<=40)
$y = $x;
else
$y=substr($x,0,40) . '...';
$output .="<td><a data-toggle=\"tooltip\" data-placement=\"top\"
title=\"{$row['name']}\"
href=\"ubah_cuprimer.php?cu={$row['id']}\"
> {$y} </td>";
}else
$output .="<td>-</td>";
$wilayah_cuprimer->id = $row['wilayah'];
$sel_kategori = $wilayah_cuprimer->get_subject_by_id();
if(!empty($sel_kategori))
$output .="<td><a href=\"#\" class=\"modal1\"
data-toggle=\"tooltip\" data-placement=\"top\"
title=\"Tekan untuk mengubah kategori artikel ini\"
name={$row['id']}>{$sel_kategori['name']}</a></td>";
else
$output .="<td><a href=\"#\" class=\"modal1\"
data-toggle=\"tooltip\" data-placement=\"top\"
title=\"Tekan untuk mengubah kategori artikel ini\"
name={$row['id']}>Tidak masuk wilayah</a></td>";
if(!empty($row['content'])){
$content = html_entity_decode($row['content']);
$content = strip_tags($content);
$z = "";
$v = $content;
if(strlen($v)<=40)
$z = $v;
else
$z=substr($v,0,40) . '...';
$output .="<td><a data-toggle=\"tooltip\" data-placement=\"top\"
title=\"{$content}\"
href=\"ubah_cuprimer.php?cu={$row['id']}\"
>{$z}</a> </td>";
}else
$output .="<td>-</td>";
if(!empty($row['tanggal']))
$output .="<td>{$row['tanggal']}</td>";
else
$output .="<td>-</td>";
if(!empty($row['id']))
$output .="<td><button class=\"btn btn-default modal2\"
name=\"{$row['id']}\"
data-toggle=\"tooltip\" data-placement=\"top\"
title=\"Tekan untuk menghapus layanan ini\" ><span
class=\"glyphicon glyphicon-trash\"></span></button></td>";
else
$output .="<td>-</td>";
$output .="</tr>";
echo $output;
}
And here is my $wilayah_cuprimer->get_subject_by_id(); function
public function get_subject_by_id(){
global $database;
$sql = "SELECT * ";
$sql .= "FROM ".self::$nama_tabel;
$sql .= " WHERE id = :id" ;
$sql .= " LIMIT 1";
$database->query($sql);
$database->bind(":id",$this->id);
$database->execute();
$array = $database->fetch();
return $array;
}
Good that you make the transition to PDO. It's better to do it now, then to find out some day that you can't upgrade PHP, because it would break your application.
As far as I can tell, $database->query($sql); only prepares a statement. That is the first step, but after that you need to execute it as well. You already have the $database->execute() method for that, but you don't call it in your insert, update and delete functions.
Apart from that issue, it would even be better if you used bind parameters for the updates too, and leave escaping strings up to the database.
It's hard to test your class in its entirety, but I hope this gives you some ideas. I added comments to describe the steps.
public function update(){
global $database;
// Don't need 'clean' attributes if you bind them as parameters.
// Any conversion you want to support is better added in $database->bind,
// but you don't need, for instance, to escape strings.
$attributes = $this->attributes();
// Place holders for the parameters. `:ParamName` marks the spot.
$attribute_pairs = array();
foreach($attributes as $key => $value){
$attribute_pairs[] = "{$key}=:{$key}";
}
$sql ="UPDATE " .self::$nama_tabel." SET " .
join(", ", $attribute_pairs) .
" WHERE id = :UPDATE_ID";
$database->query($sql);
// Bind the ID to update.
$database->bind(':UPDATE_ID', $this->id);
// Bind other attributes.
foreach($attributes as $key => $value){
$database->bind(":$key", $value);
}
// Execute the statement.
$database->execute();
// Return affected rows. Note that ->execute also returns false on failure.
return($database->affected_rows() == 1) ? true : false;
}
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>
I have 3 files:
DB.class.php - which handles all the databases.
Site.class.php - contains a function to return the latest entries in a database.
index.php - trying to print the array passed.
I am trying to pass an array into index.php from Site.class.php which is using a function from DB.class.php to put the mysql results into an associative array.
index.php:
<?php
// index.php
include 'classes/Site.class.php';
$site = new Site();
print_r($site->latestBookmarks());
?>
Site.class.php:
<?php
// Site.class.php
require_once 'DB.class.php';
class Site {
function latestBookmarks() {
$result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");
$db = new DB();
return $db->processRowSet($result);
}
}
?>
DB.class.php:
<?php
// DB.class.php
class DB {
protected $db_name = "project";
protected $db_user = "root";
protected $db_pass = "root";
protected $db_host = "localhost";
// Open up a connection to the database.
public function connect() {
$connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
mysql_select_db($this->db_name);
return true;
}
// Takes a MySQL row and returns an associative array where the keys in the array are the column names in the row set.
public function processRowSet($rowSet, $singleRow=false) {
$resultArray = array();
while ($row = mysql_fetch_assoc($rowSet)) {
array_push($resultArray, $row);
}
if ($singleRow === true)
return $resultArray[0];
return $resultArray;
}
// Select rows from the database.
public function select($table, $where) {
$sql = "SELECT * FROM $table WHERE $where";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
return $this->processRowSet($result, true);
return $this->processRowSet($result);
}
// Update a current row in the database.
public function update($data, $table, $where) {
foreach ($data as $column => $value) {
$sql = "UPDATE $table SET $column = $value WHERE $where";
mysql_query($sql) or die(mysql_error());
}
return true;
}
// Insert a new row into the database.
public function insert($data, $table) {
$columns = "";
$values = "";
foreach ($data as $column => $value) {
$columns .= ($columns == "") ? "" : ", ";
$columns .= $column;
$values .= ($values == "") ? "" : ", ";
$values .= $value;
}
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
mysql_query($sql) or die(mysql_error());
return mysql_insert_id();
}
}
?>
A few problems I noticed:
You run a query in function latestBookmarks before you connect to the db;
In your function connect you connect to a database, but the result is discarded immediately, $connection is lost as soon as the function finishes.
You have no connection to the database when you run this line:
$result = mysql_query("SELECT url, title FROM site ORDER BY id DESC");
You will need to adjust your code to send the query string to the DB instance for processing. You can add a method to DB to execute mysql_query, and pass the query in like from Site:: latestBookmarks() like this:
$db = new DB();
$db->executeQuery("SELECT url, title FROM site ORDER BY id DESC");
return $db->processRowSet();