making abstract pdo class - php

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;
}

Related

Binding Parameters Issues

I have looked at all of the other questions asked on SO and had no luck finding the problem in my code. I am trying to update a Database with an Update() method. My Insert() method is up and running, but I receive the above error when I run the code. It seems to be an error when binding my values. Would someone please give me some advice? Thank you.
<?php
class DB{
private static $_instance = null;
private $_pdo,$_query,$_error = false, $_result, $_count = 0, $_lastInsertID = null;
private function __construct(){
try{
$this->_pdo = new PDO('mysql:host='.DB_HOST.';port=3307;dbname='.DB_NAME , DB_USER, DB_PASSWORD);
}catch(PDOException $e){
die($e->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = []){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
//binds paramaters
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()){
$this->_result = $this->_query->fetchALL(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
$this->_lastInsertID = $this->_pdo->lastInsertId();
} else{
$this->error = true;
}
}
return $this;
}
public function insert($table,$fields=[]){
$fieldString = '';
$valueString = '';
$values = [];
foreach( $fields as $field => $value){
$fieldString .= '`'. $field . '`,';
$valueString .= '?,';
$values[] = $value;
}
$fieldString = rtrim($fieldString, ',');
$valueString = rtrim($valueString, ',');
$sql = "INSERT INTO {$table} ({$fieldString}) VALUES ({$valueString})";
if(!$this->query($sql, $values)->error()){
return true;
}else{
return false;
}
}
public function update($table, $id, $fields = []){
$fieldString = '';
$values = [];
foreach($fields as $field => $value){
$fieldString .= ' ' . $field . ' = ?,';
}
$fieldString = trim($fieldString);
$fieldString = rtrim($fieldString, ',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE id = {$id}";
$obj = $this->query($sql,$values);
dnd($obj);
if(!$this->_query($sql,$values)->error()){
return true;
}
return false;
}
public function error(){
return $this->_error;
}
}
?>
<?php
class Home extends Controller{
public function __construct($controller,$action){
parent::__construct($controller, $action);
}
public function indexAction(){
//die('welcome to the home controller this is the index action.');
$db = DB::getInstance();
$fields = [
'fname'=> 'Jared',
'email'=>'JBowser#123.com'];
//$contacts = $db->insert('contacts',$fields); This is how we insert to our DB.
$contacts = $db->update('contacts',3, $fields); // This is how we update our DB.
$this->view->render('home/index'); ///path from views directory **
}
}
You dont load the values array in the Update method
public function update($table, $id, $fields = []){
$fieldString = '';
$values = [];
foreach($fields as $field => $value){
$fieldString .= ' ' . $field . ' = ?,';
$values[] = $value; // <<-- Added this line
}
$fieldString = trim($fieldString);
$fieldString = rtrim($fieldString, ',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE id = {$id}";
$obj = $this->query($sql,$values);
dnd($obj);
if(!$this->_query($sql,$values)->error()){
return true;
}
return false;
}

OOP PHP - proper way to pass $_POST values from form to database_write function

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);

Value of $_GET Superglobal Not Being Passed To Processing Page

Ultimately I am trying to delete an admin by id. I know the id of the admins are making it to the list admins page because I am printing the admin id in the table next to each admin username and seeing the id. But when the delete admin link is clicked, the delete admin page is not receiving the id from the GET superglobal.
Why not?
Thanks,
CM
list_admins.php (contains the delete button at the bottom for deleting an admin)
<?php require_once("../../includes/initialize.php"); ?>
<?php //if (!$session->is_logged_in()) {redirect_to("login.php");} ?>
<?php confirm_logged_in(); ?>
<?php
$admin_set = User::find_all();
$message = "";
?>
<?php $layout_context = "admin"; ?>
<?php include("../layouts/admin_header.php"); ?>
<div id="main">
<div id="navigation">
<br />
« Main menu<br />
</div>
<div id="page">
<?php echo output_message($message); ?>
<h2>Manage Admins</h2>
<table style="border: 1px solid #000; color:#000;">
<tr>
<th style="text-align: left; width: 200px;">Username</th>
<th style="text-align: left; width: 200px;">User Id</th>
<th colspan="2" style="text-align: left;">Actions</th>
</tr>
<?php foreach($admin_set as $admin) : ?>
<tr>
<td><?php echo $admin->username; ?></td>
<td><?php echo $admin->id; ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach ?>
</table>
<br />
Add new admin
</div>
</div>
<?php include("../layouts/footer.php"); ?>
delete_admin.php
<?php require_once("../../includes/initialize.php"); ?>
<?php if (!$session->is_logged_in()) { redirect_to("login.php"); } ?>
<?php
//$admin_set = User::find_all();//This works, var_dump shows me the users are
//being returned
//var_dump($admin_set);
$admin = User::find_by_id($_GET['id']);//This returns database query failed.
var_dump($admin);
?>
user.php
<?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class User extends DatabaseObject {
protected static $table_name="admins";
protected static $db_fields = array('id', 'username', 'password', 'first_name', 'last_name');
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public function full_name() {
if(isset($this->first_name) && isset($this->last_name)) {
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
public static function authenticate($username="", $password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE username = '{$username}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
// Common Database Methods
public static function find_all() {
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function count_all() {
global $database;
$sql = "SELECT COUNT(*) FROM ".self::$table_name;
$result_set = $database->query($sql);
$row = $database->fetch_array($result_set);
return array_shift($row);
}
private static function instantiate($record) {
// Could check that $record exists and is an array
$object = new self;
// Simple, long-form approach:
// $object->id = $record['id'];
// $object->username = $record['username'];
// $object->password = $record['password'];
// $object->first_name = $record['first_name'];
// $object->last_name = $record['last_name'];
// More dynamic, short-form approach:
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
// We don't care about the value, we just want to know if the key exists
// Will return true or false
return array_key_exists($attribute, $this->attributes());
}
protected function attributes() {
// return an array of attribute names and their values
$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();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public function save() {
// A new record won't have an id yet.
return isset($this->id) ? $this->update() : $this->create();
}
public function create() {
global $database;
// Don't forget your SQL syntax and good habits:
// - INSERT INTO table (key, key) VALUES ('value', 'value')
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update() {
global $database;
// Don't forget your SQL syntax and good habits:
// - UPDATE table SET key='value', key='value' WHERE condition
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." 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;
// Don't forget your SQL syntax and good habits:
// - DELETE FROM table WHERE condition LIMIT 1
// - escape all values to prevent SQL injection
// - use LIMIT 1
$sql = "DELETE FROM ".self::$table_name;
$sql .= " WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
// NB: After deleting, the instance of User still
// exists, even though the database entry does not.
// This can be useful, as in:
// echo $user->first_name . " was deleted";
// but, for example, we can't call $user->update()
// after calling $user->delete().
}
}
?>
database.php
<?php
require_once(LIB_PATH.DS."config.php");
class MySQLDatabase{
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
if(mysqli_connect_errno()) {
die("Database connections failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
}
public function close_connection(){
if(isset($this->connection)){
mysqli_close($this->connection);
unset($this->connection);
}
}
public function query($sql){
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed yo.");
}
}
public function escape_value($string) {
$escaped_string = mysqli_real_escape_string($this->connection, $string);
return $escaped_string;
}
//database neutral functions
public function fetch_array($result_set){
return mysqli_fetch_array($result_set);
}
public function num_rows($result_set){
return mysqli_num_rows($result_set);
}
public function insert_id(){
return mysqli_insert_id($this->connection);
}
public function affected_rows(){
return mysqli_affected_rows($this->connection);
}
}//End class MySQLDatabase
$database = new MySQLDatabase();
?>
Simple answer on this one ;)
You have:
<a href="edit_admin.php?id=<?php $admin->id; ?>"> ...
<a href="delete_admin.php?id=<?php $admin->id; ?>" ...
When it should be:
<a href="edit_admin.php?id=<?php echo $admin->id; ?>">...
<a href="delete_admin.php?id=<?php echo $admin->id; ?>" ...
^^^^

insert form data with more columns into mysql database from php page using PDO

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);

CRUD - Error When Updating MySQL Database

I'm learning how to code php and I'm working on the CRUD. So far, I've got the Create and Delete methods working, but for the life of me, I cannot get Update to work. Am I missing something completely obvious here? Thank you in advance.
In my User class I have the following (Only related methods included here):
protected static $table_name="users";
protected static $db_fields = array('id', 'f_name');
public $id;
public $f_name;
public static function find_by_id($id=0) {
global $db;
$result_array = self::find_by_sql("SELECT * FROM ".static::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
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 $db;
$clean_attributes = array();
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $db->escape_value($value);
}
return $clean_attibutes;
}
public function update() {
global $db;
$attributes = $this->attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attibute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $db->escape_value($this->id);
$db->query($sql);
if ($db->affected_rows() == 1) {
echo "Yes!";
} else {
echo "No!";
}
}
In my html file, I simply have:
<?php
$user = User::find_by_id(1);
$user->f_name = "UpdatedUser";
$user->update();
?>
Well for one, your query is probably failing on account of this
$sql = "UPDATE ".static::$table_name." SET ";
being invalid. Try:
$sql = "UPDATE ".self::$table_name." SET ";

Categories