Php Connect To Db Tutorial
Before learning how to interact with a mySQL database using PHP, you must first be aware of a special type of variable in PHP known as a resource. A resource is essentially a pointer to some external entity that PHP has the ability to interact with. You will never have to display or manipulate a resource directly - instead, resources are stored in variables and passed to other functions related to the function that returned the resource.
PHP's mySQL functions make heavy use of resoruces. A connection to a mysql database is represented by a resource, and SQL queries run on that database return a resource that references the set of results returned by that query. If this all sounds complicated don't worry - the actual syntax used to deal with mySQL databases is surprisingly simple.
Connecting
In order to run queries on an external mySQL database, you must first establish a connection to that database from within your script. To do this, you will need to know the location of the database server and your username and password for accessing that server. The username and password you will need here are the ones that were allocated to your database coursework group as a whole, not your BUCS username / password.
The syntax for connecting is as follows:
$dbhost = 'midge'; // The university mySQL server is located on midge $dbuser = 'your-groups-mysql-username'; $dbpass = 'your-groups-mysql-password'; if (!$db = mysql_connect($dbhost, $dbuser, $dbpass)) { die('mySQL error: '.mysql_errno().':'.mysql_error()); }The variable $db will now contain a resource which references the connection you have just created.
Selecting the Database
One mySQL server can host any number of individual databases, each with a unique name. You must now "select" the database you wish to access. Your database name should be the same as your group password.
$dbname = 'your-groups-mysql-username'; if (!mysql_select_db($dbname)) { die('mySQL error: '.mysql_errno().':'.mysql_error()); }Should both of the above statements succeed, you will have established a connection to your database!
Important: Before saving the above code it is important that you read the next section, which describes how to prevent your database password from being available to other University students.
die() is a php construct. die() is used to terminate output of script. You can say die() is an alias of exit().

