Connecting to a MySQL Database with PHP

Sometimes you may need to connect your PHP driven website to a database. In most instances content management systems this is done through the config.php file or wp-config.php file. Below is a sample PHP script that connects to a database and shows all the fields for a specific table you specify in the code.

Important! In order for the database connection to work, you will need to create the database, add the database user, and be sure that you attach a MySQL user to the database before attempting to run the script on the server.

If you need to run a database script on your local computer, you will need to set up your computer to run ApacheMySQL, and PHP. You can do this by installing WAMP (Windows), MAMP (Mac), or XAMPP.

<?php //Sample Database Connection Script //Setup connection variables, such as database username //and password $hostname="localhost"; $username="your_dbusername"; $password="your_dbpassword"; $dbname="your_dbusername"; $usertable="your_tablename"; $yourfield = "your_field"; //Connect to the database $connection = mysql_connect($hostname, $username, $password); mysql_select_db($dbname, $connection); //Setup our query $query = "SELECT * FROM $usertable"; //Run the Query $result = mysql_query($query); //If the query returned results, loop through // each result if($result) { while($row = mysql_fetch_array($result)) { $name = $row["$yourfield"]; echo "Name: " . $name;
} } ?>

So let's take a look at the actual code and what you need to replace:

$hostname: This almost always refers to 'localhost' unless you are connecting to an external database.

$username: This is the MySQL user you want to connect with. Keep in mind the user must be assigned to the database.

$password: This is the password for the username you just entered in.

$dbname: This refers to the database name you wish to connect to.

$usertable: This is not needed to connect but in this script it refers to a specific table within the database.

$yourfield: This is not needed to connect to the database but tells the script which field to echo to the screen.

  • 1 Users Found This Useful
Was this answer helpful?

Related Articles

How do I access PhpMyAdmin to manage my database?

Each Website and E-mail hosting package offered by AbollyHost includes a control panel.  From...

How do I create a database in the hosting control panel?

Each Website and E-mail hosting package offered by AbollyHost includes a control panel.  From...