Nis Bornoe -

PHP: Basic MySQL

Page updated: February 6, 2018

Connect to a database

Estabilishing a MySQL database connection through PHP is relative simple and easy. The following example code shows 1) how to connection to the database server, and 2) how to chose a specific database on the server. "", "username", "password", and "databasename" of course needs to be replaced with your own details. If your database server is located on the same server as your web server, you can replace "" with "localhost".

// Establishing a connection to the database.
$link = mysql_connect("", "username", "password") 
	or die(mysql_error());
// Selecting the appropriate database.
	or die(mysql_error());

Get data from the a database table

This simple example will select an entire row in a database. In this example the database table contains books. All books have a unique ID besides other information such as title etc. In this example, a function is called with the ID of a given book. All information from the row is returned as in an array.

// Function that returns requested page data from the database.
function getData($bookID){
	// The right data is selected in the database.
	$data = mysql_query("SELECT * FROM books WHERE id = $bookID")
		or die(mysql_error());
	// The data is added to an array.
	$dataArr = mysql_fetch_array($data);
	// The function returns the array.
	return $dataArr;