class db {
private $_pdo ,
$_query,
$_error = false,
$_results ,
$_count = 0 ;
private function __construct () {
try {
$host = config::get('mysql/host');
$database = config::get('mysql/db');
$username = config::get('mysql/user');
$pasword = config::get('mysql/password');
$this->_pdo = new PDO("mysql:host=$host;dbname=$database", $username, $pasword);
} 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=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 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 get($table , $where) {
return $this->action("SELECT *",$table,$where) ;
}
public function delete($tabale , $where) {
return $this->action('DELETE' ,$table , $where) ;
}
public function count() {
return $this->_count ;
}
public function error() {
return $this->_error ;
}
}
index.php
$a = db::getInstance()->get('users',array('username','=','ram')) ;
if(!$a->count()) {
echo "No User" ;
} else {
echo "OK " ;
}
There is an error on index file:
Fatal error: Call to a member function count() on Boolean in line 4.
Your ->get(..) method returns the value from ->action which is a boolean
so do it so:
$a = db::getInstance(); // returns the instance
$a->get('users',array('username','=','ram')); // this return true or false
if(!$a->count()) {
echo "No User" ;
} else {
echo "OK " ;
}
Also you missed some $ at the ->action(), it need to be:
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?" ;
Misspelling of $table parameter in the delete function. And also the all symbol * is missing from the delete query on the next line.
Related
So my code was working perfectly fine, until I tried to insert to the database..
my DB.php (The problem seems to be here, I checked all the other files and nothing is causing any problems, the function I used was the Insert function and I got an error on line 37:
<?php
class DB
{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_result,
$_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 (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 = 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 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))) {
return $this;
}
}
}
return false;
}
public function get($table, $where)
{
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where)
{
return $this->action('DELETE *', $table, $where);
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
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 users (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
echo $sql;
if(!$this->query($sql, $fields)->error()){ //where my error occurred
return true;
}
}
return false;
}
}
(The data's inserted to the table but that error seems crucial and I didn't find anything about it anywhere)
I watched a tutorial on YouTube and the problem occurred here- https://youtu.be/zvXgsouIzVg?t=5258
(The full error):
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error in D:\xampp\htdocs\classes\DB.php:37 Stack trace: #0 D:\xampp\htdocs\classes\DB.php(37): PDOStatement->fetchAll(5) #1 D:\xampp\htdocs\classes\DB.php(93): DB->query('INSERT INTO use...', Array) #2 D:\xampp\htdocs\test.php(4): DB->insert('users', Array) #3 {main} thrown in D:\xampp\htdocs\classes\DB.php on line 37
Thanks in advance, that would help me a lot!
I'm learning from a tutorial online, but I can't seem to get my SQL statements to insert into the database. This is my first try at functions. I'm thinking it's the "back-tick" in my SQL statement here:
$sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES (".$values.")";`
Anyway here's my code db.php:
class DB
{
private static $_instance = null;
private
$_pdo,
$_query,
$_error = false,
$_results,
$_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'));
echo 'Connected<br>';
}
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 = array())
{
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql))
{
$r = 1;
if (count($params))
{
foreach($params as $param)
{
$this->_query->bindValue($r, $param);
$r++;
}
}
if($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
echo 'success<br>';
}
else
{
$this->_error = true;
}
}
return $this;
}
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 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 = '';
$r = 1;
foreach($fields as $field)
{
$values .= '?';
if($r < count($fields))
{
$values .= ', ';
}
$r++;
}
//die($values);
$sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES (".$values.")";
echo $sql;
if(!$this->query($sql, $fields)->error())
{
return true;
}
}
return false;
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
public function results()
{
return $this->_results;
}
public function first()
{
return $this->results()[0];
}
}
and here's my index.php:
$user = DB::getInstance()->insert('users', array(
'username' => 'Dale',
'password' => 'password',
'salt' => 'salt'
));
if($user){ echo 'true';}
I've tried removing the "back-ticks" (that's what the guy in the tutorial called them, (`), but that didn't work. I'm trying to get the index.php to insert the data into my database. Any help would be appreciated.
I would like to create a PDO function where I can pass a variable to it and get the result shown below.
The variable I would like to pass is called $range.
I would like to call the function by:
$range=$row["part_number"];
function get_range($range);
Then to get the result show below:
<?php
$range = "gmb3-30";
include ("order/connection.php");
// --------------------- Connect to the table-------------------------
$stmt = $pd->prepare('SELECT * FROM mytable WHERE part_number = :part_number');
$stmt->execute(array(
':part_number' => $range
));
$row = $stmt->fetch(PDO::FETCH_BOTH);
echo " <select name=select>";
$c = $row["price_each1"]; // price for single item
for ($i = 1; $i <= 8; $i++)
{
$b = $row["price_each" . $i];
if ($b != 0.00)
{
$d = (($c - $b) / $c) * 100;
$complete = $row[("price_break" . $i) ] . " ," . round($d) . "%";
echo "<option> ";
echo $complete . "</option>";
}
}
echo “ < / select > ”;
?>
Create a class like this and include it:
<?php
class Database{
// Define configuration
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
// Declare a new variables at the top of your class for the Database Handler and any errors.
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname.';charset=utf8;';
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
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 resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function simpleSingle(){
$this->execute();
//$this->stmt->fetch(PDO::FETCH_ASSOC);
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();
}
}
Then replace your code by this one:
function get_range($range) {
$database = null;
$database = new Database();
$database->query("SELECT * FROM mytable WHERE part_number = :part_number;");
$database->bind(':part_number', $range);
$row = $database->resulset();
if (!$row) {
// Do whatever needs to be done when you get no results
die();
} else {
echo " <select name=select>";
$i = 0;
foreach ($row as $option) {
if ($i <= 8){
$b=$option["price_each"];
if ($b !=0.00)
{
$d=(($c-$b)/$c)*100;
$complete=$option[("price_break"]. " ," .round($d)."%";
echo "<option> ";
echo $complete ."</option>";
}
$i = $i + 1;
}
}
echo “</select>”;
}
}
And in the end, call the function:
$range=$row["part_number"];
function get_range($range);
I am currently stuck..
When trying to fetch member count it returns as an array, which is not that easy to output when It's a number.. here is the code
Member.php
public function __construct() {
$this->_pdo = DB::connect();
}
public function count() {
$this->_query = $this->_pdo->query("SELECT COUNT(*) FROM members");
if(!$this->_query->error()) {
print_r($this->_query);
}
return false;
}
DB.php
private function __construct() {
try {
$this->pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/dbname'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function connect() {
if(!isset(self::$_connect)) {
self::$_connect = new DB();
}
return self::$_connect;
}
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;
}
How can I output this in the correct way?
You need to fetch the data.
$this->_query->fetchColumn();
I have a database with 5 users like hr, pay ,misc. I am using singleton database pattern to connect and execute query to these database users.
I am accessing connection information from Config Class, where i am storing connection parameters as an array.
I want to get a new connection object when i change parameter in getInstance method for example
$data1 = DB::getInsatance('common')->query("select * from Table1 (in common)");
$data2 = DB::getInsatance('misc')->query("select * from Table2 (in misc) ");
But whenever two instance methods are created with seperate users,the object initiated later in the flow is not generated
<!--
This is my DB class where my pdo parameters will change based on arguement supplied in getInstance() method --->
<?php
include_once 'Config.php';
class DB {
private static $_instance = null;
private $_pdo, $_query, $_error = false, $_results, $_count = 0;
protected $user;
private function __construct($user) {
try {
$this -> _pdo = new PDO('oci:dbname=//' . Config::get($user.'/host') . '/' . Config::get($user.'/db'), Config::get($user.'/username'), Config::get($user.'/password'));
} catch (PDOException $e) {
die($e -> getMessage());
}
}
public static function getInstance($user) {
if (!isset(self::$_instance)) {
self::$_instance = new DB($user);
}
//return $user;
return self::$_instance;
}
public function query($sql, $params = array()) {
//echo $sql.'<br>';
$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);
foreach ($this ->_results as $result) {
$this -> _count++;
}
//return $this ->_count;
} else {
$this -> _error = true;
}
}
return $this;
}
public function action($action, $table, $where = array()) {
if (count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=','like');
$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 get($table, $where) {
return $this -> action('SELECT *', $table, $where);
}
public function delete($table, $where) {
return $this -> action('DELETE', $table, $where);
}
public function getf($keys = array(), $table, $wheres = array(array(),array(),array())) {
$fields = $wheres[0];
$qoperator = $wheres[1];
$values = $wheres[2];
$operators = array('=', '>', '<', '>=', '<=');
foreach ($fields as $field) {
$this -> field = $field;
}
foreach ($qoperator as $operator1) {
$this -> operator = $operator1;
}
foreach ($values as $value1) {
$this -> value = $value1;
}
//if (in_array($operator, $operators)) {
if (count($fields) === count($values)) {
$sql = "SELECT " . implode(',', $keys) . "FROM {$table} WHERE" . implode('AND', '{$field} {$operator} ?');
} elseif (count($fields) === 0) {
$sql = "SELECT " . implode(',', $keys) . "FROM {$table} WHERE" . implode('AND', '{$field} {$operator} ?');
}
if (!$this -> query($sql, array($value)) -> error()) {
return $this;
}
//}
return false;
}
public function select($keys, $table, $where) {
return $this -> getf($keys, $table, $where);
}
public function insert($table, $fields = array()) {
$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})";
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 TENDER_ID = {$id}";
if (!$this -> query($sql, $fields) -> error()) {
return true;
}
return false;
}
public function results() {
return $this -> _results;
}
public function first() {
//return $this->results()[0];
return current($this -> results());
}
public function error() {
return $this -> _error;
}
public function count() {
return $this -> _count;
}
}
?>
Rather than setting $user and adding a new connection whenever the user changes, you can store the connections and only make a new connection when it doesn't exist:
private function __construct($user) {
try {
$this->_pdo = new PDO(
'oci:dbname=//'.Config::get($user.'/host').'/'.Config::get($user.'/db'),
Config::get($user.'/username'),
Config::get($user.'/password')
);
} catch (PDOException $e) {
die($e -> getMessage());
}
}
public static function getInstance($user) {
if (!empty(self::$_instance[$user])) {
self::$_instance[$user] = new DB($user);
}
return self::$_instance[$user];
}