Connecting to a database with PHP


If you’re going to create a website with any sort of dynamically generated content, you’re definitely going to need to connect to a database at some point. One of the most common server side scripting languages is PHP. In this post I’ll show you how to connect to your database. You’ll need to have MySQL installed and a database created

What we need first is the username and password for your database. This allows your PHP code to get access. Then, we need a location string to tell our PHP code where to find the database.



Create file (e.g. test.php) and put the following in it :

<?php

//these variables contain all our connection data 
$dbhost = 'localhost'; //this is the path to where our database lives (in this case on our local machine)
$dbuser = 'root';       //this is the username we connect to the database with
$dbpass = 'admin';    //this is the password for the user we will be using.

//now we connect. the mysql_connect function is a standard PHP function.

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
?>

that’s it! we’re now connected to the database!

Check out the next post to run an SQL query on our database and get some dynamic content.