Home
 

Customer Support

Search for keywords:

Browse by category:

How do I connect to my MySQL database?

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:


    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");
    mysql_select_db("DBNAME");
    ?>
    using the same substitutions for the bold terms as above, plus substituting DBPASSWORD with your own mysql password.

    Example:

    mysql_connect("db2.modwest.com", "joe", "secret");
    mysql_select_db("joeydb");

  • 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

User-Contributed Notes

add a note
anon -at- anonymous.com
30-May-2002 16:04
You would actually need to add the following line after the shebang:

use DBI;

11-Oct-2002 22:12
Here's how to connect using PHP

<?

//set local variables
$dbhost = "db.modwest.com"; 
$dbuser = "user"; 
$dbpass = "pass"; 
$dbname = "database"; 

//connect 
$db = mysql_pconnect($dbhost,$dbuser,$dbpass); 
mysql_select_db("$dbname",$db); 

?>

Once the connection is made you can run whatever query you want on the
database.

octava -at- octavacreations.com
11-Dec-2002 01:28
I made the following class. Enjoy it!
-------------------------
<?
class db
{
//Propiedades
	var $Host = DB_HOST;			// Hostname del servidor de MySQL
	var $Database = DB_NAME;		// Nombre Logico de la base de datos en el
servidor
	var $User = DB_USER;			// Usuario de Base de Datos
	var $Password = DB_PASS;		// Clave del usuario
	var $Link_ID = 0;			// Resultado de mysql_connect()
	var $Query_ID = 0;			// Resultado del ultimo mysql_query()
	var $Record = array();		        // Actual mysql_fetch_array()-result
	var $Row;				// Actual numero de fila
	var $Errno = 0;				// Estado de error del query
	var $Error = "";
	
//Metodos
	function halt($msg)
	{
		echo("<B>Error en Base de Datos:</B> $msg<BR>\n");
		echo("<B>Error en MySQL</B>: $this->Errno ($this->Error)<BR>\n");
		die("Session Abortada.");
	}

	function connect()
	{
		if($this->Link_ID == 0)
		{
			$this->Link_ID = mysql_connect($this->Host, $this->User,
$this->Password);
			if (!$this->Link_ID)
			{
				$this->halt("Link_ID == false, connect failed");
			}
			$SelectResult = mysql_select_db($this->Database, $this->Link_ID);
			if(!$SelectResult)
			{
				$this->Errno = mysql_errno($this->Link_ID);
				$this->Error = mysql_error($this->Link_ID);
				$this->halt("No se puede seleccionar la Base de datos
<I>".$this->Database."</I>");
			}
		}
	}

	function query($Query_String)
	{
		$this->connect();
		$this->Query_ID = mysql_query($Query_String,$this->Link_ID);
		$this->Row = 0;
		$this->Errno = mysql_errno();
		$this->Error = mysql_error();
		if (!$this->Query_ID)
		{
			$this->halt("SQL Invalida: ".$Query_String);
		}
		return $this->Query_ID;
	}

	function next_record()
	{
		$this->Record = mysql_fetch_array($this->Query_ID);
		$this->Row += 1;
		$this->Errno = mysql_errno();
		$this->Error = mysql_error();
		$stat = is_array($this->Record);
		if (!$stat)
                //if (!$this->Record)//annadida por mi
		{
			mysql_free_result($this->Query_ID);
			$this->Query_ID = 0;
		}
		return $this->Record;
	}

	function num_rows()
	{
		return mysql_num_rows($this->Query_ID);
	}

	function affected_rows()
	{
		return mysql_affected_rows($this->Link_ID);
	}

	function optimize($tbl_name)
	{
		$this->connect();
		$this->Query_ID = @mysql_query("OPTIMIZE TABLE
$tbl_name",$this->Link_ID);
	}

	function clean_results()
	{
		if($this->Query_ID != 0) mysql_freeresult($this->Query_ID);
	}

	function close()
	{
		if($this->Link_ID != 0) mysql_close($this->Link_ID);
	}
}
?>

 


beau -at- awesome2products.com
14-Apr-2009 12:20
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:

<?php

$car_make = 'Ford';
$car_model = 'Mustang';

try {
    $dbh = new PDO("mysql:host=$host;dbname=carsdb", $user, $pass);

    $stmt = $dbg->prepare('SELECT * FROM cars'
                        . ' WHERE car_make = :car_make'
                        . ' AND car_model = :car_model');
    $stmt->bindParam(':car_make', $car_make, PDO::PARAM_STR, 25);
    $stmt->bindParam(':car_model', $car_model, PDO::PARAM_STR, 25);
    $stmt->execute();

    $rows = $stmt->fetchAll();
    foreach ($rows as $row) {
        echo $row['car_make'] . '<br/>';
        echo $row['car_model'] . '<br/>';
    }

    /* close connection */
    $dbh = null;
} catch(PDOException $e) {
    echo $e->getMessage();
}

add a note

Related Questions:


How do I import delimited data into MySQL?

How do I import a MySQL dumpfile into my database?

How do I change my MySQL password?

How can I export data in CSV or tab delimited format?

Why do i get a query syntax error 1064 from MySQL when the syntax seems correct?

How do I export and move my database tables between servers or copy databases?

How do I create a .my.cnf MySQL preference file?

I can't connect to local MySQL server through socket 'mysql.sock'

How do I change MySQL timezone?

What is my database server name?

What is my MySQL Username or Database Name?

MySQL says I have too many connections.

How do I check how much disk space my database is using?

A MySQL MYI table has errors in it.

Can I connect to MySQL remotely?

Can I connect to my MySQL database from my own computer?

I can't get phpMyAdmin to work.

phpMyAdmin gives SQL syntax error when I try to create table.

How can I use odbc_connect() in my PHP scripts to connect to MySQL?

What kind of database server do you offer?

How do I import a MySQL dumpfile into my database via phpMyAdmin?

How many databases do I get?

What am I allowed to do with my MySQL database?

Will we be able to do our own MySQL admin?

How do I export a MySQL dumpfile via phpMyAdmin?

Do you offer MySQL 5?

How do I create a MYSQL dumpfile?

Browse Categories:

Getting Started, FTP, Telnet/SSH, Moving Domains, E-mail, Traffic Reports, Mailing Lists, Apache, PHP, CGI, Other Server-Side Scripting, MySQL Database, Imaging Libraries, Other Software, Billing & Terms, Control Panel, E-commerce, Pre-Sales


Modwest PHP Hosting      Copyright 2000-2009 by Modwest, Inc.      About    |    Blog    |    Community    |    Design    |    Jobs    |    Contact