Connecting to MySQL
Before you perform any operations, you need to connect to MySQL server and select a MySQL database.
Connecting to MySQL server from command line
MySQL -h HostName -u UserName -p
|-h||Keyword, followed by HOSTNAME.|
|HostName||MySQL server name|
|-u||Keyword, followed by USERNAME.|
|UserName||MySQL user name|
|-p||Asks you to enter a password.|
As soon as you enter this command, it asks you to provide a password for the user you mentioned. Supplying the appropriate password would allow you to connect to MySQL server.
Connecting to MySQL database from command line
Where DatabaseName is the database you want to select.
Disconnecting or closing MySQL server from command line
This command must be executed from the MySQL prompt.
Connecting to MySQL server and database using PHP
<?php $host="localhost"; $username="root"; $password=""; $db_name="bookinfo"; $con=MySQL_connect("$host", "$username", "$password")or die("cannot connect"); MySQL_select_db("$db_name")or die("cannot select DB"); ?>
Replace the values of the $host, $username, $password and $db_name according to your own setup. Notice that we have also selected the database with PHP, which is a must before you can fetch data from a MySQL database.
Disconnecting or closing a MySQL connection using PHP
<?php MySQL_close($con); ?>
Where $con=MySQL_connect("$host", "$username", "$password")or die("cannot connect"), shown in the previous example.
Note: It will be convenient for you if you keep the script you require to connect to and disconnect from MySQL in a PHP file and then include that file in each PHP file you are using to perform various operations on the database.
Using MySQL persistent connection with PHP
1. MySQL persistent connection is a connection which first tries to find if any identical (i.e. with the same hostname, username, and password) exists. If so, then commands followed will use that connection. If such a connection does not exist, it would create one.
2. MySQL persistent connection does not need a MySQL_close().
<?php $host="localhost"; $username="root"; $password=""; $db_name="bookinfo"; $con=MySQL_pconnect("$host", "$username", "$password")or die("cannot connect"); MySQL_select_db("$db_name")or die("cannot select DB"); ?>
Note: Use MySQL_pconnect() for better performance out of your MySQL server
Previous:MySQL Extensions for Spatial Data
Next: MySQL DATABASE
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises