Looking for a simple mySQLi class example with descriptions - php

I am looking for an example of a simple, but functional example of a class extending the mySQLi class in PHP5. I am interested in stored procedures also. Basically what I need is an example of a practical and usable class. I learn best by example and unfortunately I have been unable to find any site or book that seems to have a really solid yet simple example. All the examples I see are way to complicated so I am unable to understand or they are so simple that I might as well just instantiate the class right then and there inline. It would be great if somebody could supply me with an example like this and explain whats going on however well they can. My long term goal is to have a class that I can instantiate that deals with authentication of the database and then takes my SQL statements and supplies the output in variables.
If anyone is willing to take the time to help me out it would be much appreciated!
,Thanks

Did you check PHP PEAR MDB2 ?
http://pear.php.net/package/MDB2
Its not so simple, its the best DAL in php IMHO...

About mysqli, you can take a look at those articles :
ext/mysqli: Part I - Overview and Prepared Statements
Using ext/mysqli: Part II - Extending mysqli
(Quite old, but mysqli extension has not changed that much for a couple of years, so those should still be OK)
You could also have a look at PDO, included in PHP since version 5.1 ; it's an object-oriented API to access multiple DB engines (you don't use mysqli_query, pg_query, oci8_query or stuff like that ; only $pdo->query -- well, your SQL has to be compatible, but that's another problem ;-( )
Another approach would be using an ORM, like, for instance, Doctrine.
It's not a class that extends MySQLi, but a full Framework to abstract the DB engine - with that, you write a schema to describe you DB's structure, and you then use a "pseudo-SQL" language to send queries ; or just (for most cases) the object-oriented API that abstracts SQL.
It's a bit difficult to use, at first, but really powerful and useful (and not bad for productivity, I think, for many kind of projects)

give a try to DALMP: http://code.google.com/p/dalmp/ is support prepared statements and many cache backends

Little bit off topic but why MySQLi? PDO is much better and considered a defacto PHP standard these days. I wrote a simple PDO class a year or two ago, I can give you link if interested.

Here is a simple example of adding built in query timing to the mysqli class.
This assumes you have defined a "MyTimer" class implementing the iTimer interface. iTimer class, in it's simplest form, would record the start and stop times for the specified $key (using microtime() or getrusage() or whatever).
<?php
interface iTimer
{
public function start($key);
public function stop($key);
}
class mysqlp extends mysqli
{
function query($query, $resultmode)
{
$timer = MyTimer::getInstance();
$timer->start('mysqli::query');
$result = parent::query($query, $resultmode);
$timer->stop('mysqli::query');
return $result;
}
}
#usage
$mysqli = new mysqlp("localhost", "my_user", "my_password", "world");
$results = $mysqli->query("SELECT id FROM foo");

Related

Where to put PDO prepared statements in a DB_Connector class - in the constructor or the functions?

My web project has a class called DB_CONNECTOR where all the functions are bundled that interact with the mysql database. These would be functions like get_user(), add_user(), change_user_attribute() and many more. In each of these functions a sql query is executed and as is good practice, I use prepared statements (with named parameters).
Currently the connection to the database is established in the constructor of the class and also all the statements are prepared there. I thought this would be a good idea, so the statements are all immediatly ready for execution.
Now I realized that my use case is often to create a db_connector object, execute one or maybe two functions and then the objects lifecycle ends and at a later step a new one might be constructed (or not). So, I'm not so sure anymore if it smart to put the prepared statements in the constructor as it is forseeable that I will end up with at least 20 or likely more prepared statements.
So my question is:
is it a good idea to prepare all the statements in the constructor even if only one or two are used?
Or should I prepare them in the functions right before execution to avoid stressing the db with unneeded preparations?
This answer is based in both my experience and humble opinion, but I'll try to elaborate my arguments so it isn't just some random guy's opinion.
I don't think the database connection must be the core object in your application, let alone the only one. It'd expect to see an entirely different class for the user, so you can later have further classes for everything else. Otherwise, your application will eventually consist of a single class in a 5000 line file and your class will not be suitable to track entity data at instance level and you'll need to pass variables around in method calls. That's pretty much procedural code in OOP dress.
Also, I don't that making your User class inherits from Database (something pretty frequent nonetheless) is practical at all. Interlacing the database connection and the business logic objects doesn't really simplify application design and actually makes some parts harder.
The design of the database layer itself is pretty much standardised:
One connection per application (or more... you may need to connect to several sources!)
One statement per query.
This is exactly how PDO works.
Given that, it's easier to make the database classes just one more dependency of your entities rather than their grandparent. The injection of this dependency can be done by different means:
Make it a class property:
public function __construct(\PDO $connection)
{
$this->connection = $connection;
}
Pass it to the methods they actually needed (if not many of them):
public function getOrders(\PDO $connection)
{
$stmt = $connection->prepare('SELECT ...');
}
... or use one of those fancy dependency injection containers you can find at Packagist.
Be aware that there're also object-relational mapping (ORM), active record pattern... Those are entirely different families of solutions which may suit your needs or not depending on your use case, but not what I'm describing here.
Said that, it becomes obvious that you prepare the statements at the exact point where you need them. This design doesn't even allow otherwise ;-)

How to access a connection handle from one class in another class in php

I´m building a MVC application. My PDO connection is in /Controller/includes/Conexao and queries are in /model/DAO
As I need a prepared statement I need to use the connection handle like that:
$stmt = $db->prepare($query);
Problem is that $db is a variable in my class Conexão and I am not able to use it in DAO class. So how could I proceed?
Using old fashioned php code I could only call mysql_query but it is about to be discontinued so that´s not an option.
I would avoid using globals unless there is a VERY good reason for doing so. Look into dependency injection and singletons. There is a very nice light-weight container called Pimple that can be used for this purpose:
http://pimple.sensiolabs.org/
Another uglier solution would be using mysqli_query (only the old mysql is deprecated).

Symfony 2/Doctrine - Always available DB Connection?

Accoring to the Symfony 2 Documentation, you have to use the following PHP code to connect to the database and execute a query...
$conn = $this->get('database_connection');
$users = $conn->fetchAll('SELECT * FROM users');
I'm a complete novice with Symfony 2 but I am experienced with OOP. I was wondering if it was possible to have a globally available $conn variable that I can access from any bundle. The $conn variable would contain the value of $this->get('database_connection') so I don't have to retype $conn = $this->get('database_connection');it every time I want to make a new query.
Thanks!
global variables are most of the time NOT something you want in OOP. They are confusing when it comes to a method which deals with multiple variables and they might even be hidden by local variables. For me, working with statements like
$anything = $this->get('what.the.hell.why.arent.those.identifiers.shorter');
is as annoying as for you so I ended up in creating one subclass of Symfony\Bundle\FrameworkBundle\Controller\Controller per project which provides methods which call get with the actual identifiers. In your case I would create a method
public function getDatabaseConnection()
{
return $this->get('database_connection');
}
In general - why don't you use Doctrine for managing the DB connection? Most of the queries can be done by the ORM and this is the way to work with a real object-oriented interface to the database. Think about it, I'm also playing with Symfony2/Doctrine since some days and it really feels good. In the beginning, it might look like a hell of configuration, but once you've done the basic configs, the development is really fast! :)

Zend DB MYSQL Wrapper

All,
I have a PHP application written in Zend Framework with MVC style. I plan to use Zend_DB to connect to the MySQL database and process queries. I am looking for a wrapper class which makes it easy to use Zend_DB class. This wrapper class will have a constructor that connects to the Mysql db using Zend_DB. It will also have a method to return a singleton instance for each and every db connection made.
Something like:
$pptDB = PPTDB::getInstance();
$pptDB->setFetchMode(PPTDB::FETCH_OBJ);
$result = $pptDB->fetchRow('SELECT * FROM bugs WHERE bug_id = 2');
echo $result->bug_description;
Where class PPTDB extends Zend_DB
Is this something feasible to have? If not, how ls would you use Zend_DB in a major application?
Thanks,
AFAIK it is possible to use Zend_DB as a standalone (well, all classes in that package should also be available of course), but if you're not using the models there is little to gain from is. If you're only interested in the database abstraction I'd recommend PDO, if you want a Zend_DB wrapper Reflection can give you a nice list of properties / functions you can choose to override or not.
http://nl2.php.net/reflection
You should create adapter using Zend_Db::factory() and than use it in Zend_Db_Table_Abstract::setDefaultAdapter(). Then you can get your adapter wherever you want using Zend_Db_Table::getDefaultAdapter() or $table->getAdapter() :)

Designing a general database interface in PHP

I'm creating a small framework for my web projects in PHP so I don't have to do the basic work over and over again for every new website. It is not my goal to create a second CakePHP or Codeigniter and I'm also not planning to build my websites with any of the available frameworks as I prefer to use things I've created myself in general.
I have had no problems in designing and coding the framework when it comes to parts like the core structure, request handling, and so on, but I'm getting stuck with designing the database interface for my modules.
I've already thought about using the MVC pattern but found out that it would be a bit of an overkill for my rather small project(s).
So the exact problem I'm facing is how my frameworks modules (viewCustomers could be a module, for example) should interact with the database.
Is it (still) a good idea to mix in SQL directly into PHP code? (Would be "old way": mysql_query( 'SELECT firstname, lastname(.....))?
How could I abstract a query like the following?
SELECT firstname, lastname FROM customers WHERE id=X
Would MySQL "helper" functions like
$this->db->customers->getBy( 'id', $x );
be a good idea?
I'm not really sure because they tend to become useless when dealing with more complicated queries like the pretty much trivial one above.
Is the "Model" pattern from MVC my only real option to solve this?
What do you currently use to solve the problems shown above?
I believe you just want to get access to your DB from your module. I'd avoid using mysql_query directly from the code. Rather, going for simple model with abstracted DB access would be easy and straight-forward.
For example, you can have a file like models/Customers.php with this code:
<?php
class Customers {
public function getById($id) {
$sql = "SELECT first_name, last_name FROM customers WHERE id='$id'";
$res = $DB::getRow($sql);
return ($res);
}
}
I am assuming some kind of DB helper is already instantiated and available as $DB. Here is a simple one which uses PDO.
Now, you should include this in your module and use the following way:
<?php
include_once "models/Customers.php";
$customers = new Customers();
$theCustomer = $customers->getById(intval($_REQUEST['cust_id']));
echo "Hello " . $theCustomer['first_name']
Cheers.
have you looked into http://www.doctrine-project.org/ or other php orm frameworks (zend_db comes to mind)?
If you need speed, then use raw queries (but you should really use PDO with prepared queries).
If you want something more OOP, you can —as you suggest it— design this with helpers.
Once, I've designed something similar which had the following concept:
DB connection/handler classes (handling multi-connections to different databases and different servers such as MySQL, Oracle, etc.);
A class per action (ie. SELECT, DELETE, etc.);
Filter classes (eg. RangeFilter);
The code looked something like this:
$select = new Select('field1', 'field2', );
$result = $select->from('myTable')
->addFilter(SQLFilter::RangeFilter, 'field2')
->match(array(1, 3, 5))
->unmatch(array(15, 34))
->fetchAll();
It's a simple example of how you can build it.
You can go further and implements automated handling of table relations, field type check (using introspection on your tables), table and field alias support, etc.
It might seem to be a long and hard work, but actually, it won't take you that much time to make all these features (≈1 month).
Three tips:
Use Stored Procedures (so you can separate the php from the db)
Use PDO/MySQLi for prepared statements CALL NEWS_LIST(?, ?)
Use a Static Class for your DB. Allows you to access it within any module.
Raw SQL is still the winner for me, I like to control what I send to the server (for cases like index usage, complex JOIN clauses and etc) so I generally stay away from helper functions.
You should use PDO which already provides a lot of power and if that's not enough, you can extend that (possibly with your own functions, such as checking for hits on Memcached/APC before actually querying the database). You can also extend the class to implement your own SQL functions like:
function getUser($user_id) {
return $this->query("SELECT * FROM users WHERE id = " . (int) $user_id);
}
Of course that, from the model you should still be able to send:
$this->db->query("SELECT * FROM users WHERE id = " . (int) $user_id);
and get the same result. The functions should act merely as a shortcut and the extended class should not be included with the framework as it will be site-dependant.
The MVC pattern will fit nicely into this because you can use the database merely as a driver and your model can then transform the data into what you need. It's not hard to create a simple MVC structure and it will bring you benefits later.
You sound like me. Have you seen http://github.com/Xeoncross/micromvc and the one file ORM in http://github.com/Xeoncross/database? Dig through my code and I think you will find what you're looking for.
The solution is to use the full raw power of some queries - while still allowing ORM and query builders (like codeigniter's AR) for other things.
Both are good.
Not that i know the definitive answer (nor do i think it exists), but i thought i can just share what i have here. I use my own db 'framework', lightweight (~1000 lines currently) and easy to use. My main goal was to simplify the use of sql, not to 'hide' it from the programmer (me:). Some examples:
// row() is 'query' + 'fetch' in one
$user = $db->row("select * from users where id=25");
// the same, injection safe
$user = $db->row("select * from users where id=?", $_GET['id']);
// ? placeholders are smart
$someUsers = $db->rows("select * from users where id IN(?)", array(1, 2, 10));
// ...and even smarter
$data = array('name' => 'Joe', 'age' => 50);
$id = 222;
$db->exec("update users set ?a where id=?", $data, $id);
// 'advanced' fetch functions
$topNames = $db->vlist("select name from users order by name limit 10");
$arrayOfIds = $db->nlist("select id from users where age > 90");
// table() returns a Table Gateway
$db->table('users')->delete('where id=?', 25);
// yes, this is safe
$db->table('users')->insert($_POST);
// find() returns a Row Gateway object
$db->table('users')
->find('where name=?', 'Joe')
->set('status', 'confirmed')
->save();
Understand this: database interaction is a solved problem.
So unless you really want to do it a) for the experience or b) because you're OCD and want to know every character of the code you'll be using, then I'd choose an existing solution.
And there are many: PEAR::MDB2, Zend::Db, Creole, Doctrine, Propel, just to name a few.
I've just come off the "helper functions" path and the one thing that bugged me was that I continued adding functions in one file which grew and grew with identical or similar or defunct functions. I think the line count was at 600 and that is way to much for a single file in my opinion. This has not put me off the idea but I'll be more organised for the next trek. I'll probably split the db functions into multi files according to the db operation (select, insert etc...).
So my advice is to go try the "helper functions" and be as organized as you can.
Also, I used PDO for the first time and quite liked it. Its not as low tech as the mysql() functions or as bloat tech like some we could mention but won't. I'll be using PDO again.
It seems like there are many different opinions on this topic and as I haven't found a really satisfying answer here yet and the bounty is nearly over, I'll just write what I have come up in the last days after some trial and error:
I'm using a singleton MySQL class to handle the connection and the very basic queries as well as errors that may occur.
Single pages like /users/show/1 (using mod_rewrite) don't use raw SQL but some kind of lightweight ORM that works like in the following example:
$user = $this->db
->users
->getBy( 'id', $id );
$this->db is an instance of a Database Abstraction class with a __get( $tableName ) method. Accessing the undefined users property then triggers it. The rest explains itself; A query is formed from the arguments passed to getBy( ) (SQL escaping is also handled by it) and its results are returned as an array.
I haven't finished the whole idea yet, but adding a new user to the database could look like the following:
$user = $this->db
->users
->new;
$user->id = 2;
$user->name = 'Joe';
$user->save( );
As I said the concept isn't really completed and may have (huge) flaws in it. Yet I think that it may be easier to write, more secure and easier to maintain than plain MySQL.
Some other good sides of the whole "thing" would be that it is small, therefore rather fast and also pretty straightforward.
I know that this can't compete with the extremely powerful ORMs and frameworks already out there but I'm still creating this for some reasons mentioned in one of my comments above.
If you do plan on making a database class it may be an idea looking into making it a singleton, allowing you to use it without declaring it/creating it, as...
global $db;
$db = new db;
$db->query ('... sql ...');
is kinda redundant when you can do
db::query ('... sql ...');
I have a set of SQL functions that I use on a near regular basis to reduce what used to be a multi-line escaped lot of SQL to a single call, for example:
get_element ($table, $element, $value, $column='id');
get_row ($table, $value, $column='id');
So if you just want to get the name from a table 'customers' where the id is 4 you:
$name = db::get_element ('customers', 'name', 4);
There are also accompanying functions query_element and query_row, where you just pass it an SQL string and it returns a single element/row.
Along with the functions for insert/update, e.g.
$array = array (
'name' => 'bob jones',
'age' => 28
);
$insert_id = db::insert_array ('customers', $array);
$customer_details = db::get_row ('customers', $insert_id);
$customer_details['age'] = 30;
db:update_array ('customers, $customer_details);
Would create a new row, pull the details back out, update the age, then re-write it to the database.
Creating custom SQL access modules on a per-table basis is generally a mistake I have always found - it's better to just generically query the database using sensible functions.
If you do have to use anything with complex joins then it is always best to create function for it getCustomerInfo () for example, but if you just want a generic table value lookup making lots of custom methods just increases the chances of mistakes in one of them. Plus escaping data is very important - if you can use non-sql as much as possible and funnel it through a few core functions you can ensure everything is properly escaped fairly easily.
If you want to look at my custom database class let me know.

Categories