Lightweight MySQL Database Wrapper

Today I’m going to share a minimalistic MySQL wrapper you can use to kick start you application database development. This class is made by just seven essential methods that fit in only 101 lines of code.

Methods:

  • Affected_Rows()
  • Connect($database, $username, $password, $hostname = 'localhost', $port = 3306)
  • Disconnect()
  • Insert_ID()
  • Query($query, $type = 'assoc')
  • Quote($string)
  • Tick($string)

Affected_Rows()
Returns the number of affected rows by the previous INSERT, UPDATE, REPLACE or DELETE query.

Connect()
Connects to the MySQL server, selects the database and sets UTF-8 as the encoding.

Disconnect()
Disconnects from the database (this is optional, since the connection is automatically closed at the end of the script execution).

Insert_ID()
Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.

Query()
Runs a query against the MySQL server.
If the query statement returns a dataset (like SELECT, SHOW, DESCRIBE, EXPLAIN, etc) this method will return a two-dimensional associative array and will free the result memory for performance purposes. You can change $type to ‘object’ if you want the results to be returned as objects or change $type to ‘row’ if you prefer a numeric array. For other type of statements (INSERT, UPDATE, DELETE, TRUNCATE, DROP, etc) this method returns a boolean.

Quote()
Escapes and surrounds the value with single quotes.
Also takes care of magic quotes.

Tick()
Escapes database, table and field names with back ticks (`) so that, for instance, your database.table.password field is correctly escaped to `database`.`table`.`password` and doesn’t gets mis confused with the MySQL PASSWORD() function.

If you like it: use, abuse it and don’t forget to share it with your friends!

0 Responses to “Lightweight MySQL Database Wrapper”


  1. No Comments

Leave a Reply