How to Connect to Databases in PHP
Many web applications rely on connecting to databases to persist information and give visitors a customized experience. This requires a fair amount of knowledge about how databases work, the mechanics of SQL queries, and how to handle them at all levels of your code.
There are many ways to connect to databases in PHP. One of the recommended approaches before PHP 5.4 was to use mysqli, which offers both a procedural and object-oriented interface. PHP 5.4 introduced mysqlnd, which is the current recommendation for MySQL connections. It also provides a clean separation between database and application code.
Mysql_result() fetches a single field from a MySQL result set. It takes two or three arguments, depending on how it is used. The first is a MySQL result handle returned by mysql_db_query() or mysql_query(). The second argument is the row offset from which to fetch the field. Row offsets start at 0 for the first row, 1 for the second row and so on.
The third argument is the field to be fetched. This can be a column name, a table dot field name (tablename.fieldname) or a numeric identifier for the field (mysql_fetch_array(offset, 0, 1)).
It was common in other languages to leave open database connections even when the script was finished. This was not a good practice, however PDO now automatically closes the database connection for you - provided that you do not explicitly close it yourself. It is also important to remember that although PDO automatically sanitizes input from the database to prevent SQL injection attacks, you should still filter and sanitize all your own input to avoid possible problems with JavaScript or HTML output.