pdo disconnect from database in class - php

I wrote a class for PDO and need to disconnect PDO => ( I don't know how to do it )
I don't know code wrote is structurally correct?!
use $this->returnconn(); for db connection
Please guide me...
Sample code:
class conn {
public $inner;
public function returnconn() {
$CONF = $TMPL = array();
// The MySQL credentials
$CONF['host'] = 'localhost';
$CONF['user'] = 'root';
$CONF['pass'] = '';
$CONF['name'] = 'cmss';
$dsn ="mysql:host=".$CONF['host'].";dbname=".$CONF['name']."";
try{
$conn = new PDO($dsn,$CONF['user'],$CONF['pass']);
$conn ->exec("SET CHARACTER SET UTF8");
}catch(PDOException $e){
die($e->getMessage());
}
return $conn;
}
public function select(){
switch ($this->inner->switch){
case "select":
$sql="SELECT ".$this->inner->todo." FROM ".$this->inner->table." WHERE ".$this->inner->sql."";
$result=$this->returnconn()->prepare($sql);
/*
* this->returnconn();
*/
$result->execute();
if($result->rowCount()<=0){
return '{"msg":"empty "}';
}else{
return $result->fetch(PDO::FETCH_ASSOC);
}
break;
}
}
}
/* receive data */
$obj = new conn;
$iner = array();
$iner['table'] = 'category';
$iner['switch'] ='select';
$iner['todo'] = '*';
$iner['sql'] = '`id` IS NOT NULL ORDER BY `id` ASC';
$in = json_decode(json_encode($iner));
$obj ->inner = $in;
echo json_encode($obj ->select());
Do need a function to disconnect?

Related

Fixing max_user_connections in PHP class using PDO

I have been adapting an older abstraction layer to use PDO but I am running into user x has more than 'max_user_connections' active connections SQLSTATE[HY000] [1203] errors when looping through large sets. I have been reading on http://php.net/manual/en/pdo.connections.php but all of my attempts to unset the $dbh from within the loops result in errors from having ended the connection.
Base class looks like
class DB {
public $pdo;
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
public function __construct()
{
$this->connect();
}
private function connect()
{
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->dbname;charset=utf8;", $this->user, $this->pass, $options);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
public function __destruct()
{
$this->connection = null;
$this->pdo = null;
unset($this->pdo);
}
// CRUD methods follow including
function retrieve($where, $groupBy='', $order_by='') {
$query = "SELECT * FROM `$this->table` $where $groupBy $order_by";
$q = $this->pdo->prepare($query);
$q->execute();
$result = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,get_class($this));
// was $result = $q->fetchAll(PDO::FETCH_CLASS,get_class($this));
$this->query_log($query);
$q = null;
if ($result == 'NULL') {
return false;
} else {
return $result;
}
} // retrieve()
And an example that has the errors would be
if (in_array($_GET['type'], $types)) {
$type = $_GET['type'];
$rsObj = new ReservedSlug;
if ($type == 'artist') {
$obj = new CalendarArtist;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'event') {
$obj = new CalendarEvent;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'location') {
$obj = new Location;
$slugfield = 'UrlSlug';
$namefield = 'LocationName1';
}
$needslug = $obj->retrieve("TRIM(`$namefield`) != '' AND (`$slugfield` = '' OR `$slugfield` IS NULL) LIMIT 0,400");
if ($needslug) {
foreach ($needslug as $ns) {
$testslug = slugify($ns->$namefield);
list($reserved) = $rsObj->retrieve("`slug` = '$testslug' AND `type` = '$type'");
if (!$reserved) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug'");
if ($test) {
for ($i = 2; $i < 26; $i++) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug-$i'");
if (!$test) {
$slug = $testslug . '-' . $i;
}
}
} else { // not found in table
$slug = $testslug;
}
} else { // was reserved
$slug = false;
}
echo $ns->$namefield . " gets $slug<p>";
} // foreach needslug
} // if needslug
} // type found in array
So I need to understand how to not create new connections when an active connection is available and how to properly __destruct() these child objects. Where am I going wrong?

Passing arguments in function pdo php

I created a function to grab data from my database. I want this function to be reusable just by placing correct arguments for different tables. Here's what I've done :
public function selectdata($table, $arguments='*', $where = null){
if($this->isconnect){
//check whether users put column names in the select clause
if(is_array($arguments)){
$new_args = implode(',', $arguments);
$sql = 'SELECT '.$new_args.' FROM '.$table;
} else {
$sql = 'SELECT '.$arguments.' FROM '.$table;
}
//check whether users use the where clause
if($where != null && is_array($where)){
$where = implode(' ', $where);
$sql .= ' WHERE '.$where ;
}
$query = $this->db->query($sql);
$query -> SetFetchMode(PDO::FETCH_NUM);
while($row = $query->fetch()){
print_r($row);
}
} else {
echo 'failed, moron';
}
}
And this is the way to run the function :
$columnname = array('bookname');
$where = array('bookid','=','2');
echo $database-> selectdata('buku', $columnname, $where);
The code worked quite decently so far, but I'm wondering how I want to use $where but without $columnname in the function. How do I pass the arguments in the function?
And could you point to me the better way to create a function to grab data using PDO?
Just use a PDO class which can look like this:
<?php
class DB_Connect{
var $dbh;
function __construct(){
$host = "xxx";
$db = "xxx";
$user = "xxx";
$password = "xxx";
$this -> dbh = $this -> db_connect($host, $db, $user, $password);
}
public function getDBConnection(){
return $this -> dbh;
}
protected function db_connect($host, $db, $user, $password){
//var_dump($host, $db, $user, $password);exit();
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->getDBConnection();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
}
?>
Now you can include that class and create an object with $dbh = new DB_Connect; and call every statement you want just with the reference on $dbh->query($statement)
This is my prefered way to do this.
EDIT: If you want to use a statement on another Database, just use the __construct($db) method to pass your database name on object creation

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

Handling results from MySQLi query after MySql to MySqli conversion

I am trying to change the following code to use MySqli instead of MySql. I have removed some methods that seem unimportant to what I'm addressing here.
class db {
var $hostname,
$database,
$username,
$password,
$connection,
$last_query,
$last_i,
$last_resource,
$last_error;
function db($hostname=DB_HOSTNAME,$database=DB_DATABASE,$username=DB_USERNAME,$password=DB_PASSWORD) {
$this->hostname = $hostname;
$this->database = $database;
$this->username = $username;
$this->password = $password;
$this->connection = mysql_connect($this->hostname,$this->username,$this->password) or $this->choke("Can't connect to database");
if($this->database) $this->database($this->database);
}
function database($database) {
$this->database = $database;
mysql_select_db($this->database,$this->connection);
}
function query($query,$flag = DB_DEFAULT_FLAG) {
$this->last_query = $query;
$resource = mysql_query($query,$this->connection) or $this->choke();
list($command,$other) = preg_split("|\s+|", $query, 2);
// Load return according to query type...
switch(strtolower($command)) {
case("select"):
case("describe"):
case("desc"):
case("show"):
$return = array();
while($data = $this->resource_get($resource,$flag)) $return[] = $data;
//print_r($return);
break;
case("replace"):
case("insert"):
if($return = mysql_insert_id($this->connection))
$this->last_i = $return;
break;
default:
$return = mysql_affected_rows($this->connection);
}
return $return;
}
function resource_get($resource = NULL,$flag = DB_DEFAULT_FLAG) {
if(!$resource) $resource = $this->last_resource;
return mysql_fetch_array($resource,$flag);
}
}
This is what I've got so far:
class db {
var $hostname = DB_HOSTNAME,
$database = DB_DATABASE,
$username = DB_USERNAME,
$password = DB_PASSWORD,
$connection,
$last_query,
$last_i,
$last_resource,
$last_error;
function db($hostname, $database, $username, $password) {
$this->hostname = $hostname;
$this->database = $database;
$this->username = $username;
$this->password = $password;
$this->connection = new mysqli($this->hostname, $this->username, $this->password, $this->database) or $this->choke("Can't connect to database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($this->database)
$this->database($this->database);
}
function database($database) {
$this->database = $database;
mysqli_select_db($this->connection, $this->database );
}
function query($query, $flag = DB_DEFAULT_FLAG) {
$this->last_query = $query;
//print_r($query);
$result = mysqli_query($this->connection, $query) or $this->choke("problem connecting to DB");
while($row=mysqli_fetch_assoc($result)) {
$resource[]=$row;
}
//print($command);
//print_r($resource);print("<br>");
list($command, $other) = preg_split("|\s+|", $query, 2);
// Load return according to query type...
switch(strtolower($command)) {
case("select"):
case("describe"):
case("desc"):
case("show"):
$return = array();
while($data = $this->resource_get($resource, $flag))
$return[] = $data;
//print_r($return);
break;
case("replace"):
case("insert"):
if($return = mysqli_insert_id($this->connection))
$this->last_i = $return;
break;
default:
$return = mysqli_affected_rows($this->connection);
}
return $return;
}
function resource_get($resource = NULL, $flag = DB_DEFAULT_FLAG) {
if(!$resource)
$resource = $this->last_resource;
return mysqli_fetch_array($resource, $flag);
}
So here's the problem: I've checked the results with a print_r() and the $resource array is loading correctly, but the value of $return when checked with print_r() just ends up being "Array()". Therefore, as near as I can figure, something isn't being handled correctly in this part of the code, which is why I included the resource_get() function call:
$return = array();
while($data = $this->resource_get($resource, $flag))
$return[] = $data;
//print_r($return);
break;
If I use mysqli_fetch_row($resource, $flag) instead of mysqli_fetch_array($resource, $flag) I still get the same result, i.e. print_r($return) yields simply "Array()".
The variable $resource does not represent a mysqli_result resource object at the time you pass it into $this->resource_get(). Instead, it is already a 2D array of results since you previously ran a mysqli_fetch_assoc() loop.
To make this work with your current code, you may either remove the earlier fetch loop:
$result = mysqli_query($this->connection, $query) or $this->choke("problem connecting to DB");
// Remove this
//while($row=mysqli_fetch_assoc($result)) {
// $resource[]=$row;
//}
And later, pass $result instead of $resource into your resource_get() method since it is $result that is the resource object.
Or, you might just skip the resource_get() call entirely and return $resource directly since it already contains the result array.

could not find driver (php, PDO)

I find the error: could not find driver in the next script. I'm breaking my head over it now for some time now maybe you see the my fault.
This is my code:
class ConnectStation {
private $host = "localhost";
private $DatabaseType = "mysql";
private $database = array (
1 => "Database_one",
2 => "Database_two",
3 => "Database_true"
);
private $user1 = "MyUsername1";
private $pass1 = "MyPassword1";
private $user2 = "MyUsername2";
private $pass2 = "MyPassword2";
public function ConnectDB($user, $database){
if ($database==""){$database=1;}
try{
switch ($user){
case "ReadOnly":
$connection = new PDO("'".$this->DatabaseType.":host=".$this->host.";dbname=".$this->database[$database]."', '".$this->user1."', '".$this->pass1."'");
$connection->exec('SET CHARACTER SET utf8');
return $connection;
break;
case "Admin":
$connection = new PDO("'".$this->DatabaseType.":host=".$this->host.";dbname=".$this->database[$database]."', '".$this->user2."', '".$this->pass2."'");
$connection->exec('SET CHARACTER SET utf8');
return $connection;
break;
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
}
Oke so far the connection than the scrip i use for a query to send to the database. the code is like this:
$userCard = new ConnectStation;
$query = "SELECT username FROM users";
foreach ($this->ConnectDB('ReadOnly', 1)->query($query) as $row){
echo $row['username']."<br>";
}
Any help ore advise is welcome?
Your call to the PDO constructor is totally screwed up with unnecessary quotes and weird argument order. Just do:
$dsn = sprintf('%s:host=%s;dbname=%s', $this->DatabaseType, $this->host, $this->database[$database]);
$connection = new PDO($dsn, $this->user1, $this->pass1);

Categories