How do I connect to my MySQL database using PHP?


  1. Open a new file in your text editor
  2. Paste in the following code:

<?php
$dbhost = 'localhost';
$dbuser = '[DATABASE USERNAME]';
$dbpass = '[DATABASE PASSWORD]';

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

$dbname = '[DATABASE NAME]';
mysql_select_db($dbname);
?>

Replace [DATABASE USERNAME] with the name of your database user.  Replace [DATABASE PASSWORD] with the password for your database user.  Replace [DATABASE NAME] with the name of your database.

  1. Save this file as [NAME].php and upload it to your account.

When you want to access the database in any PHP script:

  1. Add the following line to your script:

include '[NAME].php'

  1. The database can now be queried, using standard SQL commands, and the following line:

mysql_query('QUERY')



Article ID: 9
Created On: Thu, Feb 26, 2015 at 4:53 PM
Last Updated On: Wed, Apr 29, 2015 at 9:10 AM

Online URL: https://www.heartinternet.uk/support/article/how-do-i-connect-to-my-mysql-database-using-php.html