Friday, December 10, 2010

PHP and MySQL Part 2

There are 2 methods of using mysqli. One method of using it is by object orientated and another way is by procedural.

Personally, I prefer to use object orientated.

Here is a function which I have created to connect to the database. It will return an Object if it connects successfully. If not, it will return a false which indicates that the connection failed.
$result = new mysqli ('hostname','username','password','database_name');

The 4 string values to provide mysqli are the hostname (such as localhost), username, password and the name of the database. The username and the password must be registered as a user of the database and have sufficient privileges to access the database.

Below is a simple database connect function.



We are interested to perform a query on the database so that we can obtain the results we need. How do we do so? For the object orientated method, mysqli->query will return an Object. The object will contain certain attributes such as num_rows (no. of rows), error, close, etc. For a whole list of available attributes, you can read here.

Below is a simple query function.



Now, we are able to connect to the database and perform a simple query using PHP. I will try to include some MySQL tutorials soon. =)

2 comments:

  1. Using prepared statements with PDO is even better:

    From php.net (http://www.php.net/manual/en/pdo.prepared-statements.php):

    The query only needs to be parsed once, but can be executed multiple times with the same or different parameters. (...snip...) Prepared statements use fewer resources and thus run faster.
    The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur.

    When I 'discovered' PDO I had to rewrite a lot of old SQL to use it, but the benefits were worth it.

    ReplyDelete
  2. Hey Mike! That is a wonderful advice!! Thanks for the tip! I will go and look in depth at how to do so =)
    I know that prepared statements exist but didn't really go in depth! Think I will look at them and learn how to implement them into my company's database.
    Think by implementing your method I can save a lot of headache with regards to SQL injection.. Currently I am in fact still thinking of ways on how to make the system more secure :)

    ReplyDelete