You are on page 1of 10

Follow me and receive all the latest TipoCode is also a free human-edited web link directory called

TipoDirectory. Take a moment to
free scripts: suggest a site (/page/suggesting-a-site-to-the-tipodirectory) to improve your site's SEO and increase your
Google ranking.
Top
(http://feeds.feedburner.com/tipocode)

By Email:
Custom Search Search
Enter email

Subscribe

MySQL, PHP, OOP database connection
Published September 23, 2014 by Simon Laroche (/page/who-i-am), category Database (/database)
Categories
(/jquery) (/symfony-2)
mysql database oop php
Contents [Hide]
How to connect database using Object-Oriented, PHP and MySQL
1. Introduction
2. The db.class.php file
 2.1. PDO version Introduction
(/php) (/css)  2.2. MySQL version
In this tutorial I explain how to set up a database connection, using Object-
3. Call the file
Oriented Programming (OOP), PHP and MySQL. This can be adapted with PDO
4. The SELECT Statement or MySQLi of course.
 4.1. The 1 line selection
I use this database connection system for this website.
 4.2. The multi-line selection
5. The INSERT INTO Statement It's an easy 3 steps tutorial, with code example to get and insert data in the
(/html) (/seo) 6. The UPDATE Statement database.
7. Conclusion 1. Create a db.class.php file at the root and write a class with functions ( connect ,
8. Leave a comment getOne , getAll etc.),
9. Comments (18 comments) 2. Call this file and create a new object on every pages of your website (in the
header for example),
3. Use the functions getOne , getAll or execute to select, insert or update data
(/database) in the database.

The db.class.php file

Update: first I had published the db.class.php file implementing MySQL which is deprecated. So I still
Most Popular Posts leave the first db.class.php/mysql version and I give you the db.class.php/PDO version (the one I
recommand).
Drag and Drop Multiple Files Upload
with HTML5, jQuery & FormData
(/html/drag-and-drop-multiple-files-
upload-with-html5-jquery-formdata)
PDO version
Very precise jQuery/Ajax Star Rating
Plugin Tutorial (/jquery/very-precise-
jquery-ajax-star-rating-plugin-tutorial)

jQuery editable grid system tutorial
(/jquery/jquery-editable-grid-system-
tutorial)

jQuery comment system tutorial
(/jquery/jquery-comment-system-
tutorial)

} function __destruct() { $this->disconnect(). $result = $this->conn->prepare($query). . die(). 10. $this->conn = null.$query. OOP database <?php class db { connection (/database/mysql-php-oop- private $conn. system) $this->host = 'localhost'. 65. jQuery infinite category tree private $Debug. 60. die(). } 40. tutorial) private $port. } catch (Exception $e) { die('Erreur : ' . private $password. echo 'Connection BDD failed'. 20.MySQL. //password $this->baseName = 'dbname'. $reponse = $result->fetch(). PHP. private $baseName. $ret = $result->execute(). } 25. function connect() { if (!$this->conn) { try { $this->conn = new PDO('mysql:host='. } } 45. management system (/jquery/jquery. //name of your database $this->port = '3306'. //hostname $this->user = 'user'. (/jquery/ajax-and-jquery-autocomplete. } } function getOne($query) { 55. return $reponse. } 35. Ajax and jQuery autocomplete tutorial 5. } function disconnect() { if ($this->conn) { 50. if (!$ret) { echo 'PDO::errorInfo():'. else { $this->status_fatal = false.$this->host. } function getAll($query) { 70. echo '<br />'. private $user.'.dbname='. database-connection) private $host. $this->debug = true.''. $this->connect(). 30.$this->baseName. echo 'error SQL: '. $result = $this->conn->prepare($query). function __construct($params=array()) { Top $this->conn = false. } $result->setFetchMode(PDO::FETCH_ASSOC). return $this->conn. $this->password = 'pass'. //username 15. $e->getMessage()). if (!$this->conn) { $this->status_fatal = true. infinite-category-tree-management.

$reponse = $result->fetchAll(). die(). $ret = $result->execute(). 75. Top } function execute($query) { 85. } } MySQL version (/log-in) .$query. echo '<br />'.$query. die(). return $reponse. } return $response. echo 'error SQL: '. echo '<br />'. } $result->setFetchMode(PDO::FETCH_ASSOC). 90. if (!$ret) { echo 'PDO::errorInfo():'. echo 'error SQL: '. if (!$response = $this->conn->exec($query)) { echo 'PDO::errorInfo():'. 80.

$this->BadQuery="". private $baseName. } function __destruct() { $this->disconnect(). $this->password). $cnx). echo 'Connection BDD failed'. //hostname $this->user = 'user'.com/) private (http://www. //password $this->baseName = 'dbname'. private $password. } 40. MYSQL_ASSOC). private $Debug.com/) Link Directory $conn. } } 50. Database (/database) Contact (/page/contact) 5. if ($cur == FALSE) { $errorMessage = @pg_last_error($cnx). $this->host = 'localhost'. } 45. 20. $this->conn). } 25. 55. $this->handleError($query. private $user. die(). //name of your database $this->port = '3306'. function __construct($params=array()) { Top $this->conn = false. mysql_select_db($this->baseName. $this->user. 35. 10. 60. if (!$this->conn) { $this->status_fatal = true. die(). } $cur = @mysql_query($query.tipocode. if (!$cnx || $this->status_fatal) { echo 'GetOne -> Connection BDD failed'. $this->Error=FALSE. $return = $tmp. //username 15. <?php class db { Home (http://www. $this->debug = true. private $port. $this->password = 'pass'. mysql_set_charset('utf8'. function connect() { if (!$this->conn) { $this->conn = mysql_connect($this->host.tipocode.$this->conn). } else { 65. $errorMessage). (/link-directory) jQuery (/jquery) PHP (/php) HTML (/html) CSS (/css) private $host. function disconnect() { if ($this->conn) { @pg_close($this->conn). $this->connect(). } . } return $this->conn. 70. 30. function getOne($query) { // getOne function: when you need to select only 1 line in the datab $cnx = $this->conn. } else { $this->status_fatal = false. $tmp = mysql_fetch_array($cur.

$cnx). 110. if ($this->Debug) { echo "Query : ".$use_slave=false) { // execute function: to use INSERT or UPDATE 95. } } } Call the file Add those 2 lines on every pages of your website <?php include('db. return. return $return. while($data = mysql_fetch_assoc($cur)) { array_push($return. With this Object-Oriented connection. 85. $cnx = $this->conn. } 100. if ($cur == FALSE) { $ErrorMessage = @mysql_last_error($cnx). $this->NumRows = mysql_affected_rows().$str_erreur. $return = array(). } Top mysql_query("SET NAMES 'utf8'").$query. } else { $this->Error=FALSE. die(). function getAll($query) { // getAll function: when you need to select more than 1 line in the $cnx = $this->conn. 80. $ErrorMessage).php $bdd = new db(). $this->BadQuery = $query. } @mysql_free_result($cur). we have 2 ways to do it: 1 line selection or multi-line selection The 1 line selection .class. if (!$cnx||$this->status_fatal) { return null. } function execute($query."<br>". $this->BadQuery=""."<br>".class. echo "Error : ". 120. if (!$cnx || $this->status_fatal) { echo 'GetAll -> Connection BDD failed'. $cur = mysql_query($query). } 90. } 115. $cur = @mysql_query($query. $str_erreur) { $this->Error = TRUE. $this->handleError($query. 105.php'). $data). function handleError($query. } 75. // create a new object. class db() The SELECT Statement The SELECT statement is used to select data from a database. @mysql_free_result($cur). // call db. return $return.

<?php $Users = $bdd->getAll('SELECT id.. // display the first name 5.$user['firstname'].' . .com/in/simonlaroche) : I am a Coder. You have to use the execute function <?php $query = $bdd->execute('INSERT INTO users (firstname. This new member's name is: first name: firstname1 . I'm also a wise traveller and an avid amateur photographer. foreach($Users as $user) { // display the list echo $user['id']. About Simon Laroche (https://plus.com/LandoliaPhotos) Simon Laroche on Facebook (http://www.com).landolia. echo $User['lastname'].'. You have to use the execute function <?php $query = $bdd->execute('UPDATE users SET firstname="firstname2". "lastname1" The UPDATE Statement The UPDATE statement is used to update existing records in a table. firstname. Designer.. echo $nbrUsers. 10.com/106146480175587469064) (https://twitter. last name: lastname1 . <?php $User = $bdd->getOne('SELECT id.facebook.' .'. echo $User['id']. you want to select the full users list. // return the number of lines 5. Webmaster and Expert SEO Consulting. I created the website TipoCode and many others such as Landolia: a World of Photos (http://www.'<br>'. Now you want to insert a new member in your table users .com/sim100) (http://www.linkedin. lastname FROM users WHERE lastname = "Smith"').pinterest. lastname FROM users').The 1 line selection Let say you have a table users listing website registered users. and you want to select ONE specific user.$user['lastname']. lastname="lastname2" WHERE id=20 Conclusion Now you are able to manage your database in a simple way.google. // display the last name Top The multi-line selection Now. lastname) VALUES ("firstname1". You want to update the last member inserted and change his first name to firstname2 and his last name to lastname2 . still with your table users . // display the id echo $User['firstname'].'<br>'.com/landolia) (http://www.' users in the database<br />'. // select ALL from users $nbrUsers = count($Users). the one named "Smith". } The INSERT INTO Statement The INSERT INTO statement is used to insert new records in a table. firstname.

I reply as much as I can depending of my time.. it was throwing error because i am updating with save value.. it throws error. 2017 error in your code( db connection) it won't allows update same value. 2017 Useful article. i want do update save value. Deekshith Posted on April 22. please leave a comment below. Deekshith Posted on April 22. please give me solution as soon as possible.. eg: i have 4 column in my table. 2017 Using this db connection how to do limited column update. 2017 I have to change in my previous comment. I also offer a paid support (/page/contact/#paypal).. Chris Posted on April 10. some time Deekshith Posted on April 22. when i am doing this it throwing error. Connection explanation are very clear so easy to understand. if you are in the need to adapt or create a script. and rest 2 leave as it is. please give me solution. it made for a very nice refresher course on connecting to a db with oop methods.. Leave a comment Your Name or Pseudo Top Your Email (not displayed) Your comment </> Submit Comment Comments (18 comments) Credo Systemz Posted on July 02. you may also get help from others. i want to do 2 column update. . 2017 Thanks much for this tutorial. actually.If you need help about this script.

PDO::PARAM_STR. 2016 it helped me a lot. Example: $stmt = $dbh->prepare("SELECT * FROM animals WHERE animal_id = :animal_id AND animal_name = :an /*** bind the paramaters ***/ $stmt->bindParam(':animal_id'. PDO::PARAM_INT)... } Ron Posted on November 07. /*** execute the prepared statement ***/ $stmt->execute(). 2016 Laroche@Filsjust: yes you can sanitize the statements if you need to. $bdd = new db(). thank you. 2016 Great. 5. $animal_name.=$events_sql_detail['title']. You have to check in your code page where. foreach($marquee as $events_sql_detail) { $output. shahnawaz Posted on March 06. I would like to know if i should sanitize the statements for the query. . or if that's not necessary in pdo. 2015 Simon Laroche@Suraj shrestha . 5). } $output. Simon Simon Laroche Posted on January 30. I can learn oops while using code. $animal_id. rratin Posted on September 03. Top function marquee_art(){ $marquee = $bdd->getAll("SELECT * from events where visible='yes' order by id desc"). $stmt->bindParam(':animal_name'. 2016 Hi! This tuttorial was very helpfull to me. 2017 how do i put select multiple select into function include('db. - Your class called db is declared twice.php'). Thanks.and got an error "Cannot redeclare class db".class. Filsjust Posted on January 29. Simon Laroche Posted on November 19.

2015 Laroche@timinwaedi: I have added the PDO version of the db. I didn't check because normally my queries are correct :) Marlon Posted on October 28. 2015 Laroche@Marlon : yes you're correct.php using require as require 'class. Right now it will return "status_fatal". 2015 Hi Simon. I am trying to use this scripts and little bit in confusion. require 'class. THX so much! Very useful for me. Suraj shrestha Posted on November 17. Simon Simon Laroche Posted on October 28.php tutorial which I found very helpful.class.show. and got an error "Cannot redeclare class db".php'. 2015 Top Thanks for your time and this useful tutorial.php file.add. 2015 And one thing I want to include that I called both the pages in a single page index. I tried to put both the select and insert codes on two different pages and included the database connection object on both pages like require 'class.php'. Suraj shrestha Posted on November 17. Marlon Simon Simon Laroche Posted on September 05. I see that there is a $this->status_fatal in the code But I can not find the status_fatal defined (like: private $status_fatal ). just change the file and everything will work the same way :) Simon Simon Laroche Posted on June 19.php'.database. Or isn't it necessary? With kind regards. $bdd = new db(). You can add a private $status_fatal to setup a proper message.class. Could you rewrite this tutorial using mysqli? Thanks . I noticed you are still implementing mysql which is deprecated. 2015 LarocheI recommend you to use PDO (/database/pdo-tutorial-connecting-mysql-with-pdo) timinwaedi Posted on June 18. 2015 Hi Simon Thanks for publishing the db.

com/sim100) (/page/tipodirectory-submission.facebook.com/+TipocodeWeb) How to become Premium Amazing photos Top (/page/how-to-become-premium) (http://pinterest. TipoCode Google+ Page rules) (https://plus.google.tipocode.About TipoCode About TipoDirectory Social Latest members Contact (/page/contact) The Link Directory (/link-directory) TipoCode on Twitter MillianPiyaridGianluca Michael Kaleem (https://twitter. .com (http://www. Josh Naka Guagnini Beasley Abbas tipocode) a-site-to-the-tipodirectory) My Facebook profile Who I am (/page/who-i-am) Submission rules (https://www. all rights reserved.com/TipoCodeWeb) Advertise (/page/advertising-on.com/landolia) Adding TipoDirectory links (/page/adding-tipocode-links-to-your- website) © 2014 tipocode.com). Suggesting a site (/page/suggesting.