Connect to a MySQL 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. "db.example.com", "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 "db.example.com" with "localhost".
// Establishing a connection to the database.
$link = mysqli_connect("db.example.com", "username", "password")
or die(mysqli_connect_error());
// Selecting the appropriate database.
mysqli_select_db("databasename")
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;
}
Close the database connection
When the databse connection has ended, the connection should be closed.
// Close the databse connection
mysqli_close($link);
The data is now saved in an array and can be further processed.