简体   繁体   中英

Connect to Database in Object oriented PHP

How can I create a class in oo php wherein that class will be the one that will manage the DB connection?

Sample codes or sites will do. Im using MySQL Command Client by the way.

Main problem: How can I connect to the DB so that I can insert new records, retrieve records, update records?

Thank you!

You're looking for MySQLi . It's a built-in extension since PHP 5 that you may use to query a MySQL database for data.

$mysql = new MySQLi('localhost', 'username', 'password', 'database')
$mysql->query("SELECT * FROM users");

If you're build an app from scratch, I would recommend using a PHP MVC framework package, like CakePHP or CodeIgniter. They both include a database abstraction layer which normalizes standard database functionality and keeps you from having to write SQL statements. The beauty of this is that it also allows you to change your db type later, from MySQL to say PostgreSQL, with a simple configuration change.

If you can't use an MVC, check out ADODB, which is a standalone database abstraction class:

http://adodb.sourceforge.net/

PHP's PDO (PHP Data Objects) extension is my recommendation. It has many upsides including the ability to access multiple database types including MySQL, SQLite, and PostgreSQL with the same codebase. I use it alongside a light-weight database class that extends PDO. You can find this open-source project on Google's Project Hosting at http://code.google.com/p/php-pdo-wrapper-class .

Why don't you use a mysql wrapper . It has functions to add/update/delete and a lot more utitlity functions to fasten your development time by about 40%. Ofcourse it is fully object-oriented solution.

Adodb mentioned by wmpjmurray is a good choice. You could also just create your own class that extends PDO . There are a few examples of how other people have done this in the PHP Manual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM