Getting uncaught refrence error in model.php file - php

I want to run a PHP website on localhost. I set up the server and imported the database but getting the following error...I Downloaded the website from the client c_panel public HTML folder and exported the database. I have to do changes in front-end and I have no idea of PHP(I am a Node.js developer, so if you can reference it with that to help me.). I just want to start the website locally, so that I can do the front-end changes. I'm getting the following error in my app/Models.php
Fatal error: Uncaught Error: Non-static method SB\Response::redirect() cannot be called statically in /Applications/MAMP/htdocs/app/src/sb/Model.php:475 Stack trace: #0 /Applications/MAMP/htdocs/app/src/sb/Model.php(12): SB\Model->db_error(Object(PDOException)) #1 /Applications/MAMP/htdocs/app/src/sb/DB.php(21): SB\Model->__construct() #2 /Applications/MAMP/htdocs/app/src/sb/DB.php(28): SB\DB->__construct() #3 /Applications/MAMP/htdocs/route/web.php(20): SB\DB::table('blogs') #4 /Applications/MAMP/htdocs/vendor/composer/autoload_real.php(66): require('/Applications/M...') #5 /Applications/MAMP/htdocs/vendor/composer/autoload_real.php(56): composerRequire6b60b5a5888bbd230d022934044bba82('8dab41e234cc925...', '/Applications/M...') #6 /Applications/MAMP/htdocs/vendor/autoload.php(7): ComposerAutoloaderInit6b60b5a5888bbd230d022934044bba82::getLoader() #7 /Applications/MAMP/htdocs/index.php(10): require_once('/Applications/M...') #8 {main} thrown in /Applications/MAMP/htdocs/app/src/sb/Model.php on line 475
Modal.php file:
<?php
namespace SB;
use PDO;
use PDOException;
class Model {
private $pdo = null;
public function __construct() {
try {
$this->pdo = new PDO(DSN, DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
} catch (PDOException $e) {
$this->db_error($e);
}
}
/**
* Create table
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
function create_table($table, $data) {
$sql = "CREATE TABLE IF NOT EXISTS $table (";
$num = count($data);
$sql .= "`_id` bigint(20) PRIMARY KEY NOT NULL AUTO_INCREMENT, ";
for ($i = 0; $i < $num; $i++):
$sql .= $data[$i] . ", ";
endfor;
$sql .= "`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, ";
$sql .="`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);";
$this->pdo->exec($sql);
return '<big>This code was executed. Please check manually if no table is created for the database<big> <br> '.$sql ;
}
/**
* insert
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
public function add($table, $data) {
ksort($data);
$this->pdo->beginTransaction();
$fieldNames = implode('`, `', array_keys($data));
$fieldValues = ':' . implode(', :', array_keys($data));
$sth = $this->pdo->prepare("INSERT INTO `$table` (`$fieldNames`) VALUES ($fieldValues)");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$sth->bindValue(":$key", $val);
}
$s = $sth->execute();
$this->pdo->commit();
return $s;
}
/**
* insert with get auto increment _id
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
public function addGetId($table, $data) {
ksort($data);
$fieldNames = implode('`, `', array_keys($data));
$fieldValues = ':' . implode(', :', array_keys($data));
$sth = $this->pdo->prepare("INSERT INTO `$table` (`$fieldNames`) VALUES ($fieldValues)");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$sth->bindValue(":$key", $val);
}
$res = $sth->execute();
if($res) {
return $this->pdo->lastInsertId();
} else {
return $res;
}
}
/**
* update
* #param string $table A name of table to insert into
* #param string $data An associative array
* #param string $where the WHERE query part
*/
public function modify($table, $data,$where,$where_data = []) {
ksort($data);
$fieldDetails = NULL;
foreach ($data as $key => $value) {
$fieldDetails .= "`$key`=:$key,";
}
$fieldDetails = rtrim($fieldDetails, ',');
$sth = $this->pdo->prepare("UPDATE `$table` SET $fieldDetails $where");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$val = rtrim($val," ");
$sth->bindValue(":$key", $val);
}
foreach ($where_data as $key => $value) {
$sth->bindValue(":".$key, $value);
}
return $sth->execute();
}
/**
* Fetch all
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
* #param string $where the WHERE query part
* #param string $type the return data type
*/
public function fetch_all($table,$cols = '*',$where = false, $type = null,$where_data = []) {
$statement = '';
if(!$where) {
$statement = "SELECT $cols FROM $table";
} else {
$statement = "SELECT $cols FROM $table $where";
}
$pre = $this->pdo->prepare($statement);
$pre->execute($where_data);
if(gettype($type) == 'string') {
$type = strtoupper($type);
}
if(!$type || $type == 'NUM') {
return $pre->fetchAll(PDO::FETCH_NUM);
}
else if($type == 1 || $type == 'ASSOC') {
return $pre->fetchAll(PDO::FETCH_ASSOC);
} else {
return $pre->fetchAll(PDO::FETCH_OBJ);
}
}
/**
* Fetch one
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
* #param string $where the WHERE query part
* #param string $type the return data type
*/
public function fetch_one($table,$cols = '*',$where = false, $type = null,$where_data = []) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute($where_data);
if(gettype($type) == 'string') {
$type = strtoupper($type);
}
if(!$type || $type == 'NUM')
return $pre->fetch(PDO::FETCH_NUM);
else if($type == 1 || $type == 'ASSOC' )
return $pre->fetch(PDO::FETCH_ASSOC);
else
return $pre->fetch(PDO::FETCH_OBJ);
}
public function fetch_some($table, $cols, $where, $operator) {
ksort($where);
$fields = '';
$count = count($where);
$i = 0;
foreach($where as $key=>$val):
if($i<$count-1){
$fields .= $key.' '.$operator.' :'. $key.', ' ;
}else{
$fields .= $key.' '.$operator.' :'. $key;
} $i++;
endforeach;
$pre = $this->pdo->prepare("SELECT $cols FROM $table WHERE $fields");
foreach ($where as $key => $value):
$pre->bindValue(":$key", $value);
endforeach;
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}
/**
* Fetch row
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
*/
public function fetch_row($table, $cols = '*', $where = false, $operator = '=') {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}else{
if(!is_array($where)){
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
} else {
return $this->pdo->fetch_some($table, $cols, $where, $operator);
}
}
}
/**
* Fetch rows
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
*/
public function fetch_rows($table, $cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_OBJ);
}
public function fetch_one_assoc($table,$cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}
public function fetch_one_object($table,$cols = '*',$where = false,$where_data = []) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
if(!empty($where_data))
$pre->execute($where_data);
else
$pre->execute();
return $pre->fetch(PDO::FETCH_OBJ);
}
public function fetch_all_assoc($table,$cols = '*',$where = false) {
if(!$where) {
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_ASSOC);
}
public function fetch_all_object($table,$cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
e = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_OBJ);
}
/**
* Fetch type
* #param string $table A name of table to get all data
* #param string $where the WHERE query part
*/
public function fetch_type($table, $type = PDO::FETCH_OBJ, $limit = false,$cols = '*',$where = 1) {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
$pre->execute();
if(!$limit){
return $pre->fetchAll($type);
}else{
return $pre->fetch($type);
}
}
public function fetch_sql($sql,$type = PDO::FETCH_OBJ) {
$pre = $this->pdo->prepare($sql);
$pre->execute();
return $pre->fetchAll($type);
}
public function delete_row($table,$where,$operator = '=') {
ksort($where);
$fields = '';
$count = count($where);
$i = 0;
foreach($where as $key=>$val):
if($i<$count-1){
$fields .= $key.' '.$operator.' ? AND ' ;
} else {
$fields .= $key.' '.$operator.' ?';
} $i++;
endforeach;
$pre = $this->pdo->prepare("DELETE FROM $table WHERE $fields");
foreach ($where as $key => $value):
$a[] = $value;
endforeach;
return $pre->execute($a);
}
protected function deleteData($table,$where,$where_data=[]) {
$pre = $this->pdo->prepare("DELETE FROM $table $where");
foreach ($where_data as $key => $value) {
$pre->bindValue(":".$key, $value);
}
return $pre->execute();
}
public function customeDate($date=false) {
$date=date_create("$date");
return date_format($date,"dS-M-Y");
}
public function get_json($table) {
$rows = $this->pdo->fetch_all_assoc($table);
$out = "";
foreach($rows as $row) {
$cols = array_keys($row);
if ($out != "") {
$out .= ",";
}
foreach($cols as $i=>$col){
if($i==0){
$out .= '{"'.$col.'":"' . $row[$col] . '",';
} else {
$out .= '"'.$col.'":"' . $row[$col] . '",';
}
if($i==count($cols)-1) {
$out .= '"'.$col.'":"'. $row[$col] . '"}';
}
}
}
$out ='{"records":['.$out.']}';
return $out;
}
protected function connection_close() {
$this->pdo = null;
}
private function db_error($e) {
if(IS_DEBUGG):
die('
<br><h2><br>
<center>!Config Error.<br>
<small style="color:gray">Setup your .env file. Read Following Error</small>
</center></h2>
<h3>.env file variables</h3>
<ul>
<li>DB_HOST="Enter database host name"</li>
<li>DB_USER="Enter here database user name"</li>
<li>DB_PASS="enter Database Password"</li>
<li>DB_NAME="enter Database Name"</li>
<li>DB_DRIVER="DB DIRVER like `mysql`"</li>
</ul>
<br><div style="padding:50px;"><small style="color:lightgray"><pre>' . $e . '</pre></small></div>'
);
else:
return Response::redirect('404');
endif;
}
public function fetch_qry($sql,$one=0) {
$pre = $this->pdo->prepare($sql);
$pre->execute();
if($one)
return $pre->fetch(PDO::FETCH_ASSOC);
else
return $pre->fetchAll(PDO::FETCH_ASSOC);
}
}

Update this line of code
public static function redirect($endpoint){
#header('Location:'.URL.$endpoint);
}
Or, you can create an instance of this class.
$response = new Response();
Then call this method.
$response->redirect('404');

Related

Passing array through bind_param

I'm passing an array of values through a bind_param function, the way I do this is like this:
<?php
class Query{
private $_mysqli;
/*
* #param object $mysqli
*/
public function __construct($mysqli)
{
$this->_mysqli = $mysqli;
}
/*
* #param string query
* #param string $types
* #param array $values
*/
public function read($query = "", $type = "", $params = array())
{
$query = ($query === "") ? die("Read error: Query") : $query;
$type = ($type === "") ? die("Read error: Type") : array($type);
$params = (count($params) == 0) ? die("Read error: Params") : $params;
$values = array();
foreach($params as $key => $value) {
$values[$key] = &$params[$key];
}
if ($stmt = $this->_mysqli->prepare($query))
{
call_user_func_array(array($stmt, "bind_param"), array_merge($type, $values));
$stmt->execute();
$fields = array();
for($i=0; $i<count($params); $i++){
$fields[$i] = $params[$i];
}
call_user_func_array(array($stmt, "bind_result"), $fields);
$array = array();
while($data = $stmt->fetch())
{
$array[] = $data;
}
return $array;
}
}
}
This is the way I use my function
<?php
//$mysqli is the mysqli connection
$query = new Query($mysqli);
$query_str = "SELECT * FROM users WHERE voornaam = ? AND achternaam = ?";
$types = "ss";
$params = array("Firstname", "Lastname");
var_dump($query->read($query_str, $types, $params));
?>
The part where I get stucked is:
<?php
$fields = array();
for($i=0; $i<count($params); $i++){
$fields[$i] = $params[$i];
}
call_user_func_array(array($stmt, "bind_result"), $fields);
$array = array();
while($data = $stmt->fetch())
{
$array[] = $data;
}
?>
Im not sure where it goes wrong, I have a feeling at the while loop.
hope you guys can help me making this function working :)
you are binding results , so you don't need to assign your fetched data to new variable,
mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables
to a prepared statement for result storage
while you are using call_user_func_array , and according to this comment, your loop :
while($data = $stmt->fetch())
{
$array[] = $data;
}
may be as follows:
while($stmt->fetch())
{
// params which you had bind it into bindParams
$array[] = $params;
}

when i run my program it keeps throwing these errors

Warning: Missing argument 1 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Warning: Missing argument 2 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Warning: Missing argument 3 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Warning: Missing argument 4 for MysqlDB::__construct(), called in C:\xampp\htdocs\ripplezsolution\index.php on line 9 and defined in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 10
Notice: Undefined variable: host in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
Notice: Undefined variable: username in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
Notice: Undefined variable: password in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
Notice: Undefined variable: db in C:\xampp\htdocs\ripplezsolution\phpinclude\include\MySqlDb.php on line 11
This is my MysqlDB.php code
<?php
class MysqlDB {
protected $_mysql;
protected $_where = array();
protected $_query;
protected $_paramTypeList;
public function __construct ($host, $username, $password, $db) {
$this->_mysql = new mysqli($host, $username, $password, $db)
or die('There was a problem connecting to the database');
}
public function query($query)
{
$this->_query = filter_var($query, FILTER_SANITIZE_STRING);
$stmt = $this->_prepareQuery();
$stmt->execute();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
/**
* A convenient SELECT * function.
*
* #param string $tableName The name of the database table to work with.
* #param int $numRows The number of rows total to return.
* #return array Contains the returned rows from the select query.
*/
public function get($tableName, $numRows = NULL)
{
$this->_query = "SELECT * FROM $tableName";
$stmt = $this->_buildQuery($numRows);
$stmt->execute();
$results = $this->_dynamicBindResults($stmt);
return $results;
}
/**
*
* #param <string $tableName The name of the table.
* #param array $insertData Data containing information for inserting into the DB.
* #return boolean Boolean indicating whether the insert query was completed succesfully.
*/
public function insert($tableName, $insertData)
{
$this->_query = "INSERT into $tableName";
$stmt = $this->_buildQuery(NULL, $insertData);
$stmt->execute();
if ($stmt->affected_rows)
return true;
}
public function update($tableName, $tableData)
{
$this->_query = "UPDATE $tableName SET ";
$stmt = $this->_buildQuery(NULL, $tableData);
$stmt->execute();
if ($stmt->affected_rows)
return true;
}
public function delete($tableName) {
$this->_query = "DELETE FROM $tableName";
$stmt = $this->_buildQuery();
$stmt->execute();
if ($stmt->affected_rows)
return true;
}
public function where($whereProp, $whereValue)
{
$this->_where[$whereProp] = $whereValue;
}
protected function _determineType($item)
{
switch (gettype($item)) {
case 'string':
return 's';
break;
case 'integer':
return 'i';
break;
case 'blob':
return 'b';
break;
case 'double':
return 'd';
break;
}
}
protected function _buildQuery($numRows = NULL, $tableData = false)
{
$hasTableData = null;
if (gettype($tableData) === 'array') {
$hasTableData = true;
}
// Did the user call the "where" method?
if (!empty($this->_where)) {
$keys = array_keys($this->_where);
$where_prop = $keys[0];
$where_value = $this->_where[$where_prop];
// if update data was passed, filter through
// and create the SQL query, accordingly.
if ($hasTableData) {
$i = 1;
$pos = strpos($this->_query, 'UPDATE');
if ( $pos !== false) {
foreach ($tableData as $prop => $value) {
// determines what data type the item is, for binding purposes.
$this->_paramTypeList .= $this->_determineType($value);
// prepares the reset of the SQL query.
if ($i === count($tableData)) {
$this->_query .= $prop . " = ? WHERE " . $where_prop . "= " . $where_value;
} else {
$this->_query .= $prop . ' = ?, ';
}
$i++;
}
}
} else {
$this->_paramTypeList = $this->_determineType($where_value);
$this->_query .= " WHERE " . $where_prop . "= ?";
}
}
if ($hasTableData) {
$pos = strpos($this->_query, 'INSERT');
if ($pos !== false) {
$keys = array_keys($tableData);
$values = array_values($tableData);
$num = count($keys);
foreach ($values as $key => $val) {
$values[$key] = "'{$val}'";
$this->_paramTypeList .= $this->_determineType($val);
}
$this->_query .= '(' . implode($keys, ', ') . ')';
$this->_query .= ' VALUES(';
while ($num !== 0) {
($num !== 1) ? $this->_query .= '?, ' : $this->_query .= '?)';
$num--;
}
}
}
if (isset($numRows)) {
$this->_query .= " LIMIT " . (int) $numRows;
}
$stmt = $this->_prepareQuery();
if ($hasTableData) {
$args = array();
$args[] = $this->_paramTypeList;
foreach ($tableData as $prop => $val) {
$args[] = &$tableData[$prop];
}
call_user_func_array(array($stmt, 'bind_param'), $args);
} else {
if ($this->_where)
$stmt->bind_param($this->_paramTypeList, $where_value);
}
return $stmt;
}
protected function _dynamicBindResults($stmt)
{
$parameters = array();
$results = array();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
$x = array();
foreach ($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
return $results;
}
protected function _prepareQuery()
{
if (!$stmt = $this->_mysql->prepare($this->_query)) {
trigger_error("Problem preparing query", E_USER_ERROR);
}
return $stmt;
}
public function __destruct()
{
$this->_mysql->close();
}
}
?>
and i'm calling a function insert() through index.php
<?php
ob_start();
session_start();
require_once("phpinclude/include/membersite_config.php");
require_once("phpinclude/include/MySqlDB.php");
$DB = new MysqlDB('172.90.13.97','king','mi*****hhh','kxxxx_database');
if (isset($_GET['action'])){$action = htmlentities($_GET['action']);}
else{$action = NULL;}
$mysqldb = new MysqlDB();
?>
<?php if($action=='add_cart'){?>
<?php $data=array($arrival, $departure, $result, $roomID, $category_price); $table='tb_cart';?>
<?php $this->mysqldb->insert($table, $data); ?>
<?php }?>
Problem is in this line
$mysqldb = new MysqlDB();
The constructor requries arguments which are not passed. You need to pass $host, $username, $password, $db to constructor.
Your code acutally makes no sense. You could use $DB instead of creating new object. You also use $this->mysqldb in no object context. There are plenty of errors in your code.
To fix:
Remove this line $mysqldb = new MysqlDB();
Change <?php $this->mysqldb->insert($table, $data); ?> to $DB->insert($table, $data);
Script should +- look like:
<?php
ob_start();
session_start();
require_once("phpinclude/include/membersite_config.php");
require_once("phpinclude/include/MySqlDB.php");
$DB = new MysqlDB('172.90.13.97','king','mi*****hhh','kxxxx_database');
$action = !empty($_GET['action']) ? htmlentities($_GET['action']) : null;
if ($action == 'add_cart') {
$data = array(
'arrival' => $arrival,
'departure' => $departure,
'result' => $result,
'roomID' => $roomID,
'category_price' => $category_price
);
$DB->insert('tb_cart', $data);
}

Database class, OOP - connect to mysql

This is database class:
DB.php
<?php
class DB {
public static $instance = null;
private $_pdo = null,
$_query = null,
$_error = false,
$_results = null,
$_count = 0;
private function __construct() {
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOExeption $e) {
die($e->getMessage());
}
}
public static function getInstance() {
// Already an instance of this? Return, if not, create.
if(!isset(self::$instance)) {
self::$instance = new DB();
}
return self::$instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where) {
return $this->action('DELETE', $table, $where);
}
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
return false;
}
}
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $value) {
$values .= "?";
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function update($table, $id, $fields = array()) {
$set = null;
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ', ';
}
$x++;
}
$sql = "UPDATE users SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function results() {
// Return result object
return $this->_results;
}
public function first() {
return $this->_results[0];
}
public function count() {
// Return count
return $this->_count;
}
public function error() {
return $this->_error;
}
}
I was looking this database approach and it seems very practical and useful. I'm beginner at oop and still learning. The requestQuote would look something like this:
How do I bindParam in query like this?
requestQuote = DB::getInstance()->query(""); (form DB.class)
This is code I have right now:
$request = "";
if ($_POST) {
$request = $_POST["request"];
} else if (isset($_GET["request"])) {
$request = $_GET["request"];
}
$requestQuote="%" . $request . "%";
$sql = $conn -> prepare("SELECT * FROM users WHERE concat(name, ' ',lastname, ' ', user_id) LIKE :request limit " . (($page * 50)-50) . ",50");
$sql->bindParam(":request", $requestQuote);
$sql -> execute();
$results = $sql -> fetchAll(PDO::FETCH_OBJ);
When I put it like this, then pagination works. But I need search form... and that won't work...
$sql= DB::getInstance()->query(
"SELECT * FROM users
WHERE (category='admin')
LIMIT " . (($page* 5)-5) . ",5");
#Paul was close but you got one more issue:
Check this part of the class:
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
It is not binding with named place holder, you need to change the code:
$limit = ($page * 50)-50;
$params = array('%lolcats%', $limit);
$query =
"SELECT * FROM users
WHERE concat(name, ' ',lastname, ' ', user_id)
LIKE ?
LIMIT ?,50";
$results = DB::getInstance()->query($query, $params);
or change the class code to bind by placeholder, something along the following lines:
#$params = array(':request' =>'%lolcats%', ':limit'=>$limit);
if(count($params)) {
foreach($params as $key=>$value) {
$this->_query->bindValue($key, $value);
}
}
Looking at this class, the second argument of query function is an optional array of parameters so use this to pass the parameters for your request:
$params = array(':request' => 'lolcats');
$limit = $page - 1 * 50;
$query = sprintf(
"SELECT * FROM users
WHERE concat(name, ' ',lastname, ' ', user_id)
LIKE :request
LIMIT %d,50",
$limt
);
$results = DB::getInstance()->query($query, $params);

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

Sql query using pdo in mysql

I have a very simple select query using pdo but it is not working.
The generic sql query is
$sql = "select * from table where type != 'address' and type != 'multipleimage'";
Now in pdo I have
$fieldtype = array('address','multipleimage');
$query = $this->db->prepare("SELECT * from table where
(type not in $type) and (userid !=:userid) ");
$query->execute(array(':userid' => 2, $fieldtype ));
Now getting notice + warning
Notice is ' Array to string conversion....'
Warning is 'Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation.....'
Why don't you use NOT IN clause like:
$sql = "select * from table where type not in ('address','multipleimage')";
Something like this, you may have to do some minor changes
<?php
$fieldtype = array('address','multipleimage');
$inQuery = implode(',', array_fill(0, count($fieldtype), '?'));
$db = new PDO(...);
$stmt = $db->prepare(
'select * from table where type not in(' . $inQuery . ')'
);
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $fieldtype);
$stmt->execute();
?>
I have created my own ORM like class called DBConnection.php. It does all CRUD functionalities for any table in the specified database. It uses PDO as well. Feel free to play with it, customize and use in your code if you would like to....
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of DBConnection
*
* #author alemayehu
*/
require_once '../lib/PHPDebug.php';
class DBConnection {
private static $_instance = null;
private $_pdo;
private $_query;
private $_error = false;
private $_results;
private $_count = 0;
private function __construct() {
try{
$this->_pdo = new PDO("mysql:host=".Config::get("mysql/host").";dbname=".Config::get("mysql/db"),
Config::get("mysql/username"),Config::get("mysql/password"));
} catch (Exception $ex) {
PHPDebug::printLogText("Connection Failed : ". $ex->getMessage() , "../lib/debug.txt");
die($ex->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DBConnection();
}
return self::$_instance;
}
public function fetchResultSet($sql, $params = array()){
//var_dump($params);passed
$this-> _error = false;
if($this-> _query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}else{
echo 'something wrong with the array';
}
var_dump($this->_query);
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}else{
$this->_error = true;
}
}
return $this->_results;
}
public function query($sql, $params = array()){
$this-> _error = false;
if($this-> _query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}else{
$this->_error = true;
}
}
return $this;
}
public function error(){
return $this->_error;
}
private function action($action, $table, $where = array()){
if(count($where) === 3){
$operators = array('=', '<', '>', '<=', '>=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)){
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if( !$this->query($sql, array($value))->error() ){
return $this;//was this
}
}
}
}
public function get($table, $where){
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where){
return $this->action('DELETE', $table, $where);
}
public function insert($table, $fields = array()){
if(count($fields)){
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field){
$values .= '?';
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES( {$values} )";
//var_dump($sql);
if( ! $this->query($sql, $fields)->error()){
return true;
}
}
return false;
}
public function update($table, $id, $fields){
$set = '';
$x = 1;
foreach ($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)){
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE user_id = {$id}";
if(! $this->query($sql, $fields)->error()){
return true;
}else{
return false;
}
}
public function fetchAllRecords($table, $where){
return $this->query("SELECT * FROM {$table} WHERE $where");
}
public function count(){
return $this->_count;
}
public function getResults(){
return $this->_results;
}
public function first(){
return $this->_results[0];
}
}//end class

Categories