Home Guides Glossary

Connecting to MySQL Using PHP

You can access MySQL databases directly through PHP scripts. This lets you read and write data to your database directly from your website.

  1. Connect to your MySQL server using the mysql_connect statement. For example:

    $con = mysql_connect('HOSTNAME','USERNAME','PASSWORD');

    For help with your mysql_connect information, see Viewing Your Database Details with Shared Hosting Accounts.

  2. Select the database that you want to access using mysql_select_db. For example:

    mysql_select_db('DATABASENAME', $con)
    Where 'DATABASENAME' is the name of your database — this also displays on your database's details page.

After establishing the connection and selecting the database, you can query it using PHP.

To help you create your own connection string, we've included an example below.

Example PHP MySQL connection string

This connect string will look in a database (your_dbusername, find a particular table (your_tablename), and then list all values in that table for a field (i.e. column) you specify (your_field).

<?php
//Sample Database Connection Syntax for PHP and MySQL.
//Connect To Database
$hostname="your_hostname";
$username="your_dbusername";
$password="your_dbpassword";
$dbname="your_dbusername";
$usertable="your_tablename";
$yourfield = "your_field";
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
# Check If Record Exists
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if($result)
{
while($row = mysql_fetch_array($result))
{
$name = $row["$yourfield"];
echo "Name: ".$name."<br/>";
}
}
?>

For more information, see the MySQL Functions page at php.net.

More GoWebsite Articles
How many simultaneous connections can one MySQL database have? Which MySQL features do you disable on hosting accounts? What are the limitations for MS SQL? How do you limit MySQL databases? What Do I Do When I Receive an Updateable Query Error? Viewing Your Database Details with Shared Hosting Accounts Connecting to a MySQL Database Using ASP.NET

Domain Registration

Pay less for website domain names. Register your own .com, .net or .org for as low as $10.18 per year. We have everything you need to get online with your new domain.

Website Builder

Build an amazing website in just under an hour with Website Builder. Take advantage of designs created just for your industry and then customize them to reflect your one-of-a-kind idea.

Website Security

Protect your website and keep customers safe. Your comprehensive Website Security solution. Get peace of mind by securing your websites.

cPanel Hosting

Everything needed to give your website the high-performance home it deserves.  Protect transactions and secure your customer's data with a SSL Certificate
Copyright © 2005 - 2024.  All rights reserved.  Privacy Policy