Different ways to connect to a database using PHP


I’m currently reading “Build Your Own Database Driven Web Site Using PHP & MySQL” and I have a simple question.

In this book to connect to a database you connect to the server and to the database separately, this is the code…

$link = mysqli_connect('localhost','root','root');
	$output= 'Unable to connect to the database server';
	include 'output.html.php';
	$output='Unable to locate database';

But I have seen people connecting like this…

$connect = mysqli_connect("localhost","root","root","jokes")
or die ('Unable to locate database');

A lot less code…

What is the main difference between these two methods, does it metter which one you use? or its simply different versions of PHP?

Thanks a lot!

this is a special class, check this:

this is more a question of how do you want to handle the catastrophic failure to connect to your database.

Using die offers the programmer far less sophisticated options, but is quick and easy to write, so might be useful to debug as you develop - you are not likely to leave it like that in your finished product.

In the finished product you may want to variously:

log the error
recover graciously with helpful messages about what the user should do
try a secondary database/table
send an email
… and so on

Thanks a lot for your help!

There are many different ways of connecting to MySQL database with PHP based on the users, but here is a straight way

$db=mysql_connect($host, $user_name, $pwd);
if (mysql_error() > “”) print mysql_error() . “<br>”;
mysql_select_db($database_name, $db);
if (mysql_error() > “”) print mysql_error() . “<br>”;

This is the straight forward way to easily connect your MySQL database with PHP. You can easily use this code in a function and then call that function:

Thanks a lot for your reply!