Navigation
Navigation
MySQL Database
How do I connect to my MySQL database?
Applies to: Grid System
Before you can use MySQL at all, you need to create a database for yourself on your Control Panel. Once you have created a database, there are a few ways you can connect to it:
- At a shell prompt you type all one 1 single line:
- mysql -u DBUSERNAME -h DBSERVER -p DBNAME
with the following replacements of the bolded terms above:
- Replace DBSERVER with the correct database servername for your site.
- Replace DBUSERNAME with your own mysql username.
- Replace DBNAME with your own mysql databasename.
Example:
- mysql -u joe -h db.joesmith.com -p joeydb
If you don't know your MySQL Username or MySQL Databasename, go here.
You will then be prompted for your MySQL password. If you don't know what that is, go here to set it to something that you will remember.
If you use preferences set in a .my.cnf file, the connection command would be much shorter, just:
- mysql
Once at the MySQL prompt, you can then issue SQL commands directly to the MySQL server. For correct SQL syntax, see the MySQL Manual.
- To connect from a PHP script, just put this in your file:
mysql_connect("DBSERVER", "DBUSERNAME", "DBPASSWORD");
using the same substitutions for the bold terms as above, plus substituting DBPASSWORD with your own mysql password.
mysql_select_db("DBNAME");
?>
Example:
- mysql_connect("db2.modwest.com", "joe", "secret");
- mysql_select_db("joeydb");
- mysql_connect("db2.modwest.com", "joe", "secret");
- To connect from a perl script, put this in your file:
#!/usr/bin/perl
use DBI;
$database = "DBNAME";
$hostname = "DBSERVER";
$port = "3306";
$username = "DBUSERNAME";
$password = 'DBPASSWORD';
$dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";
$dbh = DBI->connect($dsn, $username, $password) or die("Could not connect!");
$sql = "SELECT * FROM mytable";
$sth = $dbh->prepare($sql);
$sth->execute;
while(($column1, $column2) = $sth->fetchrow_array)
{
print "C1 = $column1, C2 = $column2n";
}
$dbh->disconnect;
where DBNAME, DBUSERNAME, and DBPASSWORD are your database name, database username and database password, and where DBSERVER is your database server.
- For connections from your own computer or from outside our network, see this FAQ
Last update: 2010-09-29 16:25
Author: FAQ Admin
Revision: 1.3
You can comment this FAQ
Comment of Anonymous:
Here's how to connect using PHP
Once the connection is made you can run whatever query you want on the database.
Added at: 2002-10-11 22:12
Comment of Anonymous:
I made the following class. Enjoy it!
-------------------------
Added at: 2002-12-11 01:28
Comment of Anonymous:
You would actually need to add the following line after the shebang:
use DBI;
Added at: 2002-05-30 16:04
Comment of Anonymous:
Besides connecting to MySQL with PHPs generic MySQL extension, it is preferred to use PDO with prepared statements. This reduces the vulnerability of SQL injection. Example:
Added at: 2009-04-14 12:20
