Вы находитесь на странице: 1из 10

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

ctory. 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)
MySQL, PHP, OOP database <?php
class db {
connection (/database/mysql-php-oop-
private $conn;
database-connection)
private $host;
Ajax and jQuery autocomplete tutorial 5. private $user;
(/jquery/ajax-and-jquery-autocomplete- private $password;
private $baseName;
tutorial)
private $port;
jQuery infinite category tree private $Debug;
management system (/jquery/jquery- 10.
infinite-category-tree-management- function __construct($params=array()) { Top
$this->conn = false;
system)
$this->host = 'localhost'; //hostname
$this->user = 'user'; //username
15. $this->password = 'pass'; //password
$this->baseName = 'dbname'; //name of your database
$this->port = '3306';
$this->debug = true;
$this->connect();
20. }

function __destruct() {
$this->disconnect();
}
25.
function connect() {
if (!$this->conn) {
try {
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->baseName.'',
30. }
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}

35. if (!$this->conn) {
$this->status_fatal = true;
echo 'Connection BDD failed';
die();
}
40. else {
$this->status_fatal = false;
}
}

45. return $this->conn;


}

function disconnect() {
if ($this->conn) {
50. $this->conn = null;
}
}

function getOne($query) {
55. $result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
60. echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetch();
65.
return $reponse;
}

function getAll($query) {
70. $result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
75. echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
80.
return $reponse;
Top
}

function execute($query) {
85. if (!$response = $this->conn->exec($query)) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
90. }
return $response;
}
}

MySQL version

(/log-in)
<?php
class db {
Home (http://www.tipocode.com/) private
(http://www.tipocode.com/) Link Directory
$conn; (/link-directory) jQuery (/jquery) PHP (/php)
HTML (/html) CSS (/css) private $host;
Database (/database) Contact (/page/contact)
5. private $user;
private $password;
private $baseName;
private $port;
private $Debug;
10.
function __construct($params=array()) { Top
$this->conn = false;
$this->host = 'localhost'; //hostname
$this->user = 'user'; //username
15. $this->password = 'pass'; //password
$this->baseName = 'dbname'; //name of your database
$this->port = '3306';
$this->debug = true;
$this->connect();
20. }

function __destruct() {
$this->disconnect();
}
25.
function connect() {
if (!$this->conn) {
$this->conn = mysql_connect($this->host, $this->user, $this->password);
mysql_select_db($this->baseName, $this->conn);
30. mysql_set_charset('utf8',$this->conn);

if (!$this->conn) {
$this->status_fatal = true;
echo 'Connection BDD failed';
35. die();
}
else {
$this->status_fatal = false;
}
40. }

return $this->conn;
}

45. function disconnect() {


if ($this->conn) {
@pg_close($this->conn);
}
}
50.
function getOne($query) { // getOne function: when you need to select only 1 line in the datab
$cnx = $this->conn;
if (!$cnx || $this->status_fatal) {
echo 'GetOne -> Connection BDD failed';
55. die();
}

$cur = @mysql_query($query, $cnx);

60. if ($cur == FALSE) {


$errorMessage = @pg_last_error($cnx);
$this->handleError($query, $errorMessage);
}
else {
65. $this->Error=FALSE;
$this->BadQuery="";
$tmp = mysql_fetch_array($cur, MYSQL_ASSOC);

$return = $tmp;
70. }
@mysql_free_result($cur);
return $return;
}
75.
function getAll($query) { // getAll function: when you need to select more than 1 line in the
$cnx = $this->conn;
if (!$cnx || $this->status_fatal) {
echo 'GetAll -> Connection BDD failed';
80. die();
}
Top

mysql_query("SET NAMES 'utf8'");


$cur = mysql_query($query);
85. $return = array();

while($data = mysql_fetch_assoc($cur)) {
array_push($return, $data);
}
90.
return $return;
}

function execute($query,$use_slave=false) { // execute function: to use INSERT or UPDATE


95. $cnx = $this->conn;
if (!$cnx||$this->status_fatal) {
return null;
}

100. $cur = @mysql_query($query, $cnx);

if ($cur == FALSE) {
$ErrorMessage = @mysql_last_error($cnx);
$this->handleError($query, $ErrorMessage);
105. }
else {
$this->Error=FALSE;
$this->BadQuery="";
$this->NumRows = mysql_affected_rows();
110. return;
}
@mysql_free_result($cur);
}

115. function handleError($query, $str_erreur) {


$this->Error = TRUE;
$this->BadQuery = $query;
if ($this->Debug) {
echo "Query : ".$query."<br>";
120. echo "Error : ".$str_erreur."<br>";
}
}
}

Call the file


Add those 2 lines on every pages of your website

<?php
include('db.class.php'); // call db.class.php
$bdd = new db(); // create a new object, class db()

The SELECT Statement


The SELECT statement is used to select data from a database.

With this Object-Oriented connection, we have 2 ways to do it: 1 line selection or multi-line selection

The 1 line selection


The 1 line selection
Let say you have a table users listing website registered users, and you want to select ONE specific user, the
one named "Smith".

<?php
$User = $bdd->getOne('SELECT id, firstname, lastname FROM users WHERE lastname = "Smith"');
echo $User['id'].'<br>'; // display the id
echo $User['firstname'].'<br>'; // display the first name
5. echo $User['lastname']; // display the last name
Top

The multi-line selection


Now, still with your table users , you want to select the full users list.

<?php
$Users = $bdd->getAll('SELECT id, firstname, lastname FROM users'); // select ALL from users

$nbrUsers = count($Users); // return the number of lines


5.
echo $nbrUsers.' users in the database<br />';

foreach($Users as $user) { // display the list


echo $user['id'].' - '.$user['firstname'].' - '.$user['lastname'];
10. }

The INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.

Now you want to insert a new member in your table users . This new member's name is: first name:
firstname1 , last name: lastname1 .

You have to use the execute function

<?php
$query = $bdd->execute('INSERT INTO users (firstname, lastname) VALUES ("firstname1", "lastname1"

The UPDATE Statement


The UPDATE statement is used to update existing records in a table.

You want to update the last member inserted and change his first name to firstname2 and his last name to
lastname2 .

You have to use the execute function

<?php
$query = $bdd->execute('UPDATE users SET firstname="firstname2", lastname="lastname2" WHERE id=20

Conclusion
Now you are able to manage your database in a simple way.

About Simon Laroche (https://plus.google.com/106146480175587469064)


(https://twitter.com/LandoliaPhotos)
Simon Laroche on Facebook (http://www.facebook.com/sim100)
(http://www.pinterest.com/landolia) (http://www.linkedin.com/in/simonlaroche) : I am a Coder,
Designer, Webmaster and Expert SEO Consulting, I'm also a wise traveller and an avid amateur
photographer. I created the website TipoCode and many others such as Landolia: a World of Photos
(http://www.landolia.com)...
If you need help about this script, please leave a comment below. I reply as much as I can depending of
my time, you may also get help from others.
I also offer a paid support (/page/contact/#paypal), if you are in the need to adapt or create a
script...

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, 2017
Useful article.. Connection explanation are very clear so easy to understand...

Deekshith Posted on April 22, 2017


error in your code( db connection) it won't allows update same value, it throws error.

Deekshith Posted on April 22, 2017


I have to change in my previous comment, actually, it was throwing error because i am
updating with save value, please give me solution, i want do update save value, some time

Deekshith Posted on April 22, 2017


Using this db connection how to do limited column update, eg: i have 4 column in my table, i
want to do 2 column update, and rest 2 leave as it is, when i am doing this it throwing error.
please give me solution as soon as possible.

Chris Posted on April 10, 2017


Thanks much for this tutorial, it made for a very nice refresher course on connecting to a db
with oop methods.
shahnawaz Posted on March 06, 2017
how do i put select multiple select into function

include('db.class.php');

$bdd = new db();

Top
function marquee_art(){

$marquee = $bdd->getAll("SELECT * from events where visible='yes' order by id desc");

foreach($marquee as $events_sql_detail)
{
$output.=$events_sql_detail['title'];
}

$output;

Ron Posted on November 07, 2016


Great. Thanks. I can learn oops while using code.

rratin Posted on September 03, 2016


it helped me a lot, thank you.

Simon Simon Laroche Posted on January 30, 2016


Laroche@Filsjust: yes you can sanitize the statements if you need to. Example:

$stmt = $dbh->prepare("SELECT * FROM animals WHERE animal_id = :animal_id AND animal_name = :an

/*** bind the paramaters ***/


$stmt->bindParam(':animal_id', $animal_id, PDO::PARAM_INT);
5. $stmt->bindParam(':animal_name', $animal_name, PDO::PARAM_STR, 5);

/*** execute the prepared statement ***/


$stmt->execute();

Filsjust Posted on January 29, 2016


Hi!
This tuttorial was very helpfull to me.
I would like to know if i should sanitize the statements for the query, or if that's not necessary in pdo.

Simon Laroche Posted on November 19, 2015


Simon
Laroche@Suraj shrestha
- and got an error "Cannot redeclare class db". -

Your class called db is declared twice... You have to check in your code page where.
Suraj shrestha Posted on November 17, 2015
And one thing I want to include that I called both the pages in a single page index.php using
require as

require 'class.show.php';
require 'class.add.php';

Suraj shrestha Posted on November 17, 2015


Top
Thanks for your time and this useful tutorial.
I am trying to use this scripts and little bit in confusion. 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.database.php';
$bdd = new db();

and got an error "Cannot redeclare class db".

Simon Simon Laroche Posted on October 28, 2015


Laroche@Marlon : yes you're correct. Right now it will return "status_fatal". You can add a
private $status_fatal

to setup a proper message. I didn't check because normally my queries are correct :)

Marlon Posted on October 28, 2015


Hi Simon,

THX so much! Very useful for me.

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

).
Or isn't it necessary?

With kind regards,


Marlon

Simon Simon Laroche Posted on September 05, 2015


Laroche@timinwaedi: I have added the PDO version of the db.class.php file, just change the file and
everything will work the same way :)

Simon Simon Laroche Posted on June 19, 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.class.php tutorial which I found very helpful. I noticed you are still
implementing mysql which is deprecated. Could you rewrite this tutorial using mysqli?
Thanks
About TipoCode About TipoDirectory Social Latest members

Contact (/page/contact) The Link Directory (/link-directory) TipoCode on Twitter


MillianPiyaridGianluca
Michael
Kaleem
(https://twitter.com/TipoCodeWeb)
Advertise (/page/advertising-on- Suggesting a site (/page/suggesting- 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.facebook.com/sim100)


(/page/tipodirectory-submission- TipoCode Google+ Page
rules) (https://plus.google.com/+TipocodeWeb)
How to become Premium Amazing photos Top
(/page/how-to-become-premium) (http://pinterest.com/landolia)
Adding TipoDirectory links
(/page/adding-tipocode-links-to-your-
website)

© 2014 tipocode.com (http://www.tipocode.com), all rights reserved.

Вам также может понравиться