How do I query a MySQL database from a PHP script?

Use the following outline to connect and begin querying the MySQL server from within your PHP scripts. You should connect to localhost for database connections, not the external IP or hostname of the server..

1. Connect to the MySQL Server

Use the following statement to connect to the database server. Substitute the username and password for those that have been created in the control panel and have given adequate permissions to this database.

mysql_connect('localhost','USERNAME','PASSWORD');

2. Select Your Database

Use the following statement to select the database you wish to connect to. Make sure you substitute your database name.

mysql_select_db("DATABASENAME");

3. Executing A Query

You are now ready to execute your queries. Most problems that arise with your scripts will be caused by incorrect permission settings or syntax errors within the code.

mysql_query("QUERY");

4. Close the connection

Once your script has finished with the database, it should close the connection.

mysql_close();

  • 129 Users Found This Useful
Was this answer helpful?

Related Articles

How do I connect to my MySQL database from a Perl CGI script?

Perl's DBI module provides an interface to MySQL databases for CGI scripts. A commented example...

How do I connect to MySQL with ASP?

This applies to Windows Hosting accounts only.You will need to use a DSNless connection which can...

How do I set up the MySQL connection using Dreamweaver?

1. Open Dreamweaver2. Click File>New3. Choose “Dynamic Page” in left frame and then “PHP” (or...

Can I rename my database getting rid of the 'web-' part of the name?

Unfortunately this isn't possible as the convention is required for backing up the data on the...

What are the default / allowed privileges for MySQL databases?

By default on all MySQL databases the current privileges are given -SELECT, INSERT, UPDATE,...