Jump to content

Recommended Posts

Okay, after settling on using dpo, thanks mainly to thorpe, I'm now trying to put it into a class that I can use quickly.

what I'm wondering is whether this is the right way to go about using pdo, to make it as re-usable as I can, or if there is a prefered way.

This is what I've got (It's very basic):

<?php
class mysql_funcs{
function connect($host, $db, $u, $p){
	try{
		$this->dbh = new PDO('mysql:host=' . $host . ';dbname=' . $db, $u, $p, array(PDO::ATTR_PERSISTENT => true));
		$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}catch(Exception $e) {
		die('Error: ' . $e->getMessage());
	}
}

function insert($table, $fields, $vals){
	$i = 1;
	try{
		$this->dbh->beginTransaction();
		$stmt = $this->dbh->prepare("INSERT INTO `:table` (:fields) VALUES (:vals)");
		$stmt->bindParam(':table', $table);
		$stmt->bindParam(':fields', $fields);
		$stmt->bindParam(':vals', $vals);
		$stmt->execute();
		$this->dbh->commit();
		echo 'success<br />';
	}catch(Exception $e) {
		$this->dbh->rollBack();
		echo "Failed: " . $e->getMessage() . '<br />';
		return false;
	}
}
}

$con = new mysql_funcs;
$con->connect('localhost', 'test', 'root', 'LifesPeachy');
$con->insert('test', 'test', 2);
?>

Link to comment
https://forums.phpfreaks.com/topic/88615-dpo-and-classes/
Share on other sites

Firstly, your limitting your classes usage straight up by naming it mysql_*. PDO is a database abstraction layer that makes using any number of different databases possible without modyfying code. You should take advantage of this fact.

 

Secondly, I wouldn't let the class itself echo exceptions (or any output really), exceptions should be dealt with by the calling code. This way you can handle exceptions how you like without needing to modify the class at all.

 

Thirdly, while I probably wouldn't use any custom insert method at all I definately wouldn't hard code transactions into it. Transactions really only need be used when you have multiple inserts depending on each other. ie: If one fails you need to undo them all.

 

If I was going to create the functionality of your class (note, this isn't how I would do things) it would probably be more like....

 

<?php

<?php

class MyPdoException extends Exception{}

class MyPdo {

  private $dbh;

  public function __construct($driver, $db, $host=null, $user=null, $pass=null){
    try {
      switch($driver) {
        case 'sqlite':
          $this->dbh = new PDO("sqlite:$db");
        case 'mysql':
          if (!is_null($host) && !is_null($user) && !is_null($pass)) {
            $this->dbh = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
          } else {
            throw new MyPdoException("Missing required peram for the mysql driver");
          }
        case 'pgsql':
          if (!is_null($host) && !is_null($user) && !is_null($pass)) {
            $this->dbh = new PDO("pgsql:host=$host dbname=$db user=$user password=$pass");
          } else {
            throw new MyPdoException("Missing required peram for the pgsql driver");
          }
        }
      }
    } catch (MyPdoException $e) {
        throw new MyPdoException($e->getMessage());
    } catch (PDOException $e) {
        throw new MyPdoException("Unable to connect to database");
    }
  }

  function insert($table, $fields, $vals) {
    $stmt = $this->dbh->prepare("INSERT INTO `:table` (:fields) VALUES (:vals)");
    $stmt->bindParam(':table', $table);
    $stmt->bindParam(':fields', $fields);
    $stmt->bindParam(':vals', $vals);
    return $stmt->execute();
  }

}

try {
  $pdo = new MyPdo('mysql','test','localhost','thorpe','foo');
  $pdo->insert('test', 'test', 2);
} catch (MyPdoException $e) {
  // log error using $e->getMessage(), client need never know the reason.
  echo "Unable to perform insert";
}

?>

 

All that being said PDO itself is already an OOP based abstraction layer. Have a play with it out of the box before deciding what your really need to abstract further.

Link to comment
https://forums.phpfreaks.com/topic/88615-dpo-and-classes/#findComment-453878
Share on other sites

okay. I see where you're coming from and it would be best to handle exceptions outside of the class, which I would've done anyway. This was just a basic code I threw together to see if I was on the right tracks.

Which obviously I'm not ::)

 

How else am I supposed to have an easily accessible 'insert/select from and then handle that data' type of function.

The best I could think of was to create a class with individual functions utilising the pdo classes.

Link to comment
https://forums.phpfreaks.com/topic/88615-dpo-and-classes/#findComment-453893
Share on other sites

How else am I supposed to have an easily accessible 'insert/select from and then handle that data' type of function.

 

If you want to go down that path, your probably best looking at an ORM (object relational mapper). There are a few good ones around, but developing your own would be a rather large project in itself.

 

xPDO is a nice light weight one that I've used with quite a bit of success.

 

Link to comment
https://forums.phpfreaks.com/topic/88615-dpo-and-classes/#findComment-454055
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.