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
- Email FAQ to a friend
- Printable version
- Rss Feed
- Last Updated: 5-31-07

{ 2 comments… read them below or add one }
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
Other than displaying the value twice, this worked great for me! Thanks