How to: Connect to my MySQL Database server using command line and php

Q. How do I connect to my MySQL database server using command line (over ssh) or using PHP?

A. You can connect to MySQL database server using mysql command line client or using programming language such as PHP or perl.

Task: Use command line client - mysql

Genral syntax is as follows:
mysql -u DBUSER -h DBSERVERNAME -p

So at a shell prompt you type all one single line to connect to database server install on localhost for vivek user:
$ mysql -u vivek -h localhost -p

Supply the password when prompted for password. Make sure you replace vivek and localhost name with your database username and hostname.

Task: Use PHP to connect to MySQL

Type the following PHP code:

<?php
   $link = mysql_connect("localhost", "USERNAME", "PASSWORD");
   mysql_select_db("DATABASE");

   $query = "SELECT * FROM TABLE";
   $result = mysql_query($query);

   while ($line = mysql_fetch_array($result))
   {
      foreach ($line as $value)
       {
         print "$value\n";
      }
   }

    mysql_close($link);
?>

Make sure you replace USERNAME and PASSWORD with your database user name and password. Also, replace TABLE and DATABASE with the valid table and database names from your database.

Upload PHP file and type url http://yourdomain.com/myscript.php

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 2 comments… read them below or add one }

1 sr 04.06.09 at 12:30 pm

hi i am trying to connect to my sql with this code

but i get an erorr of exceeding the time or long period more than 60 sec

would u help me

2 Michael 04.15.09 at 6:34 pm

Other than displaying the value twice, this worked great for me! Thanks

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post: How to Access the FAT32 files or filesystem from Linux system

Next post: Gnome Linux Disable / Turn Off Hardware Beep Sound For Terminal