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
E-mail this to a friend
Printable version
Related Other Helpful FAQs:
- How do I access MySQL server from the shell prompt (command line)?
- PHP not connecting to a MySQL database server
- Mysql user creation - setting up a MySQL new user account
- How to access MySQL database using Perl
- MySQL command to show list of databases on server
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!



Recent Comments
Yesterday ~ 3 Comments
Yesterday ~ 7 Comments
Yesterday ~ 4 Comments
Yesterday ~ 8 Comments
Yesterday ~ 45 Comments