MySQL: connecting, selecting db, validating table(s) in 3 lines of code

Bill

84.***.***.***
983 days ago

MySQL: connecting, selecting db, validating table(s) in 3 lines of code

As it says on the tin can, just 3 lines of code to connect to a MySQL database and validate that everything's in order, without left-over variables.

PHP code:


// Fail if we can't authenticate.
@mysql_connect('localhost', $username, $password) OR die(mysql_error());

// Fail if we can't select the database.
@mysql_select_db($database) OR die(mysql_error());

// Fail if a required table doesn't exist or has crashed. You can replicate this line for any number of tables you want to validate.
@mysql_query('SELECT 1 FROM ' . $table . ' LIMIT 0') OR die(mysql_error());

Bill

84.***.***.***
983 days ago
Another thing I'd like to add is...

PHP code:


@mysql_query('SET NAMES utf8;');



...just after the DB select line.

This to prevent having screw-ups with international characters. Obviously the HTML pages and relevant table fields also need to be set to UTF-8 but the many methods of doing that belongs to another topic.