Encapsulates a PDO class, hoping that Csdn's Daniel will point out the shortcomings

Source: Internet
Author: User
Tags dsn rowcount
Encapsulates a PDO class, hoping Csdn's Daniel will point out the shortcomings.

Masters, come on!

  "SET NAMES",);p ublic function __construct ($dsn, $user = ", $pass =", $persistent = false, $charset = "UTF8") {$this-&G T;options[pdo::mysql_attr_init_command]. = $charset; if ($persistent) {$this->options[pdo::attr_persistent] = True ;} $this->pdo = new PDO ($DSN, $user, $pass, $this->options);} /** global property settings, including: Column name format and error prompt type you can use a number to directly use the parameter */public function setAttr ($param, $val = ") {if (Is_array ($param)) {foreach ($ param as $key = $val) {$this->pdo->setattribute ($key, $val);}} Else{if ($val! = ") {$this->pdo->setattribute ($param, $val);} Else{return false;}}} /** generate a compiled SQL statement template you can use? : The form of name returns a statement object */public function prepare ($sql) {if (empty ($sql)) {return false;} $this->statement = $this->pdo->prepare ($sql); return $this->statement;} /** executes SQL statements, typically used to increment, delete, update, or set the number of rows returned */public function exec ($sql) {if (empty ($sql)) {return false;} Try{return $this->pdo->exec ($sql);} catch (Exception $e) {return $e->getmessage ();}} The/** executes a query with a return value, and the return pdostatement can be chained toClass encapsulated operation gets the data */public function query ($sql) {if (empty ($sql)) {return false;} $this->statement = $this->pdo->query ($sql); return $this->statement;} /** Open transaction */public function BeginTransaction () {return $this->pdo->begintransaction ();} /** COMMIT TRANSACTION */public function commit () {return $this->pdo->commit ();} /** transaction rollback */public function RollBack () {return $this->pdo->rollback ();} Public Function Lastinertid () {return $this->pdo->lastinsertid ();} * * Pdostatement class action Encapsulation **///** let the template Execute SQL statements, 1, execute compiled 2, compile */public function execute ($param = "") {if (Is_array ($param) when executing. ) {Try{return $this->statement->execute ($param);} catch (Exception $e) {//return $this->errorinfo (); return $e->getmessage ();}} Else{try{return $this->statement->execute ();} catch (Exception $e) {/* return error message format [0] = 42s22 [1] = 1054 [2] = Unknown column ' col ' in ' field List ' ret    Urn $this->errorinfo (); */return $e->getmessage ();}}} /** parameter 1 Description: Pdo::fetch_both is also the default, both have (Index, association) pdo::fetch_assOC Associative array pdo::fetch_num index Pdo::fetch_obj object Pdo::fetch_lazy object is accompanied by QueryString query SQL statement Pdo::fetch_bound if Bindcolumn is set, Use this parameter to */public function fetch ($fetch _type = Pdo::fetch_assoc) {if (Is_object ($this->statement)) {return $this- Statement->fetch ($fetch _type);} return false;} /** parameter 1 Description: Pdo::fetch_both is also the default, both have (Index, association) PDO::FETCH_ASSOC Associative Array pdo::fetch_num index Pdo::fetch_obj object Pdo::fetch_ Column parameter 2 You can specify the column you want to get pdo::fetch_class specify your own defined class Pdo::fetch_func the custom class handles the returned data pdo_fetch_bound if you need to set Bindcolumn, Then use this parameter parameter 2 Description: Given the class or function to process the result */public function fetchall ($fetch _type = pdo::fetch_assoc, $handle = ") {if (empty ($handle)) {return $this->statement->fetchall ($fetch _type);} return $this->statement->fetchall ($fetch _type, $handle);} /** returns the result as an object in the same way as FETCH (pdo::fetch_obj) */public function Fetchobject ($class _name) {if (Empty ($clss _name)) {return $ This->statement->fetchobject ();} return $this->statement->fetchobject ($class _name);} Public Function fetchcolumn ($intColumn = 0) {return $this->statement->fetChcolumn ($intColumn);} /**public function Bindcolumn ($array =array (), $type =extr_overwrite) {if (count ($array) >0) {Extract ($array, $type);} $this->statement->bindcolumn ()}*//** bind variables to placeholders in a reference way (you can perform only once prepare, perform multiple bindparam to achieve the effect of reuse) */public function Bindparam ($parameter, $variable, $data _type = ' STR ', $length = 0) {switch ($data _type) {case ' STR ': $data _type = PD O::P aram_str;break;case ' INT ': $data _type = PDO::P aram_int;break;default: $data _type = "; break;} return $this->statement->bindparam ($parameter, $variable, $data _type, $length);} /** returns the number of rows in the statement recordset */public function RowCount () {return $this->statement->rowcount ();} Public function count () {return $this->statement->rowcount ();} Public Function ColumnCount () {$this->statement->execute (); return $this->statement->columncount ();} Public Function Getcolumnmeta ($intColumn) {return $this->statement->getcolumnmeta ($intColumn);} /** Close */public function close () {return $this->statement->closecursor ();} Public FuNction Closecursor () {return $this->statement->closecursor ();} /** return error message also includes error number */private function ErrorInfo () {return $this->statement->errorinfo ();} /** returns the error number */private function ErrorCode () {return $this->statement->errorcode ();} Simplified operation public Function Insert ($table, $data) {if (!is_array ($data)) {return false;} $cols = Array (), $vals = Array (), foreach ($data as $key = = $val) {$cols [] = $key; $vals [] = "'". $val. "'";} $sql = "INSERT into {$table} ("; $sql. = Implode (",", $cols). ") VALUES ("; $sql. = Implode (", ", $vals).") "; return $this->exec ($sql);} Public Function Insertbind ($table, $arrayData) {if (!is_array ($arrayData)) {return false;} $vals = Array_keys ($arrayData); $cols = Array ();/* $arrayobject = new Arrayobject ($arrayData); $iterator = $arrayobje Ct->getiterator (); while ($iterator->valid ()) {$vals [] = ': '. $iterator->key (). "; $iterator->next ();} */$c = implode (', $vals); $cols = Array_filter (Explode (': ', $c)); $sql = "INSERT into {$table} ("; $sql. = imPlode (",", $cols). VALUES ("; $sql. = Implode (", ", $vals).") "; $this->statement = $this->pdo->prepare ($sql), $this->statement->execute ($arrayData), return $this- >statement->rowcount ();} Public Function Update ($table, $data, $where) {if (!is_array ($data)) {return false;} $set = Array (), foreach ($data as $key = = $val) {$set [] = $key. "='" . $val. "'";} $sql = "UPDATE {$table} SET"; $sql. = Implode (",", $set); $sql. = "WHERE". $where; return $this->exec ($sql);} Public Function Updatebind ($sql, $arrayWhere) {if (empty ($sql) | |!is_array ($arrayWhere)) {return false;} $this->statement = $this->pdo->prepare ($sql), $this->statement->execute ($arrayWhere), return $this- >statement->rowcount ();} Public Function Delete ($table, $where) {if (empty ($table) | | empty ($where)) {return false;} $sql = ' delete from {$table} wher E ". $where; return $this->exec ($sql);} Public Function Deletebind ($sql, $arrayWhere) {if (empty ($sql) | |!is_array ($arrayWhere)) {return false;} $tHis->statement = $this->pdo->prepare ($sql); $this->statement->execute ($arrayWhere); return $this- >statement->rowcount ();}}? >




After all, in a project, it is impossible to write about PDO's own stuff everywhere. Do not say that PDO has been packaged, no need to package the same nonsense.


Reply to discussion (solution)

A few suggestions:
1. If I
$db = new Pdox;
$a = $db->query ($sql 1);
$b = $db->query ($sql 2);
Print_r ($a->fetchall ());
Print_r ($b->fetchall ());
May I? Obviously it is not possible, because
$this->statement = $this->pdo->query ($sql);
The results of the previous query were overwritten the next time.
2, the transaction (Transaction) operation should be packaged as a whole, only pass in a group of SQL and hide related operations
3. Do not consider using stored procedures
4. Pdox can be directly inherited from PDO without having to copy PDO already has a method


Overall is good, but there are some ways to feel too trivial, can be necessary to integrate together

A few suggestions:
1. If I
$db = new Pdox;
$a = $db->query ($sql 1);
$b = $db->query ($sql 2);
Print_r ($a->fetchall ());
Print_r ($b->fetchall ());
May I? Obviously it is not possible, because
$this->statement = $this->pdo->query ($sql);
The results of the previous query were overwritten the next time.
2, the transaction (Transaction) operation should be packaged as a whole, only pass in a group of SQL and hide related operations
3. Do not consider using stored procedures
4. Pdox can be directly inherited from PDO without having to copy PDO already has a method


Thank you for your valuable advice, I just want it to be simpler to operate.
1, as you can cite this example, there is a workaround.
2, business I seldom use, also do not know how to encapsulate. It would be better if you could give me a hint.
3, stored procedures are seldom used.
4, copy PDO method, just want to use on and PDO is like, convenient directly write PDO friends directly use this class. There is no need to study too much. Unlike other database classes, after learning the original database operation, but also to learn a new database operation, it may be very simple, but learning is time.



Overall is good, but there are some ways to feel too trivial, can be necessary to integrate together


How can the integration be more concise??

The purpose of encapsulation is to simplify the operation, the less commonly used does not have to encapsulate the

Class Pdox extends PDO {  //executes various SQL instructions and can be extended by parameter $param  function query ($sql, $param =null) {}  //Query and return a single record 
  function Fetch ($sql) {};  Querying and returning multiple records as an array  function Fetchall ($sql) {}}
The database class can meet the needs of most applications as long as there are three of these methods.
Because it inherits from PDO, the original method of PDO is no less

@xuzuning

$db = new Pdox;
$a = $db->query ($sql 1);
$b = $db->query ($sql 2);
Print_r ($a->fetchall ());
Print_r ($b->fetchall ());

Shouldn't there be a lot of programmers in this kind of notation? If so, consider abandoning this operation support first. This is a big problem if my class is having problems with efficiency or concurrency.

Are there any errors or irregularities inside this class?

Daniel, please speak a lot.

Nested even recursive queries are often used when reading a classification tree, how can they not say much?
Well, it's not necessary to make a message board.

Simple insertion of data:
$data = Array (': Title ' = ' $title, ': content ' = $content);
$pdo = new Pdox;
$lastID = $pdo->insertbind (' article ', $data);


To modify the data:
$data = Array (': title ' = = $title, ': id ' = $id);
$sql = ' Update article set title=:title where Id=:id ';
$yesorno = $pdo->updatebind ($sql, $data);

Delete data:
$data = Array (': id ' = = $id);
$sql = ' Delete article where Id=:id ';
$yesorno = $pdo->deletebind ($sql, $data);

The main thing is this kind of writing, can save a lot of code volume. This is the key to my writing this class.

Nested even recursive queries are often used when reading a classification tree, how can they not say much?
Well, it's not necessary to make a message board.



That's what you're talking about, and it needs to be used in recursion. If you want to use this kind of friends, pay attention.

I will try to optimize the PHP code or use other methods instead of recursion, because recursion consumes resources.

Thank you for reminding me.

That's a pretty tangled look.

That's a pretty tangled look.



Tangled up???

I think it's very convenient to manipulate the data.

Daniel, go on.

The purpose of encapsulation is to simplify the operation, the less commonly used does not have to encapsulate the

Class Pdox extends PDO {  //executes various SQL instructions and can be extended by parameter $param  function query ($sql, $param =null) {}  //Query and return a single record 
  function Fetch ($sql) {};  Querying and returning multiple records as an array  function Fetchall ($sql) {}}
The database class can meet the needs of most applications as long as there are three of these methods.
Because it inherits from PDO, the original method of PDO is no less



Do not know the moderator can have a better PDO operation class???
Can you contribute one.

Not much!
In addition, the pretreatment part is not encapsulated

/** * Converts an array to an SQL statement * @param array $where the arrays to be generated * @param string $font connection string. */final Public Function Sqls ($where, $font = ' and ') {# first saves bindcolumn $this->bindcolumn = array (); if (Is_array ($where ) {$sql = "; foreach ($where as $key = = $val) {$sql. = $sql? "$font ' $key ' =: $key": "' $key ' =: $key"; $this->bindcolumn = Array ($key, $val);} return;} else {return $where;}}
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.