skip to content rich footer

stevenclark.com.au

subscibe to the StevenClark.com.au rss feed

SQL Tip: Open Connection, Query, Close

A very simple tip to novice backend PHP (Hypertext Preprocessor) programmers is to understand that database connections have an overhead - a database connection should be opened, the tables queried with SQL (Structured Query Language), and then the connection is closed. Generally I keep the database connection in two functions within a discrete file that is re-usable throughout the website. Open, run my queries, and then close the connection. It’s hardly rocket science.

One novice mistake is to forget, or decide not to, close database connections. And another is to keep opening new database connections for every query.

A more seasoned approach to running queries is to open the door once, grab what you really need, and close it again as you leave. If you’re using those variables on another page then store them for ongoing use in a session, a cookie or pass them as a URL encoded string in name / value pairs.

So my small tip for the day is that if you’re going to run SQL queries in your PHP keep the process as simple and mechanical as possible. Open a connection, query the database, and close the connection on your way out.

Articles are licenced under a Creative Commons Licence but copyright of images is retained by © Steven Clark 2007 - 2008

One Response to “SQL Tip: Open Connection, Query, Close”

  1. SQL ConnectToDatabase Function : StevenClark.com.au

    [...] « SQL Tip: Open Connection, Query, Close [...]

skip to top of page

Currently Reading

Andy Clarke's Transcending CSS: the fine art of web design has been sitting on my bookshelf for several months and I've finally made the time to read it from end to end. My favourite thing about this book from the outset is that it's a designer's book, rather than a technician's manual, for web designers. The artwork and direction in Transcending CSS is enhanced by the attention to detail in the feel and texture of the book itself, the size of it's pages and the feel of the cover in your hands. It's definately a book that affords the act of being read. Looking forward to it.