Page Content

Tutorials

How to connect access with MySQL Database?

Connect MySQL Database

An essential first step in data management or database-application integration is connecting to a MySQL database. The command-line client, graphical user interface (GUI) tools, and scripting languages like PHP are some of the ways this can be accomplished.

Connecting using the command-line client (mysql)

An interactive tool for connecting to a MySQL server, executing queries, and viewing results is the mysql command-line client. Both batch and interactive modes are available.

The mysql command usually requires a MySQL login and password in order to connect to a MySQL server. To connect, use the following basic syntax, which will ask for your password:

mysql -u [username] -p

For example, mysql -u root -p would be used to connect as the root user. The client will ask you to input the password once you enter this command. It is better to enter the password when prompted following the -p option rather than typing it right after -p without a space, since the latter may cause a ‘insecure’ warning.

The hostname must also be specified with the -h option if the MySQL server is operating on a separate computer. The format changes to mysql -h hostname -u username -p. It is frequently possible to omit the hostname for local connections. For local connections, you may also use –socket to specify a socket file.

You will get the mysql> prompt and introduction information after a successful connection. The client is prepared to receive SQL statements, as indicated by this prompt. To be transmitted to the server for execution, SQL statements must conclude with a semicolon (;) or \g. They can be typed across multiple lines. Help, quit, and clear are examples of client commands that don’t need a terminator. To clear the buffer, use the \c command.

You can type QUIT or quit at the mysql> prompt to end your connection to the MySQL server. You can also press Control+D on Unix systems.

Specifying a database when connecting

When you connect to the MySQL server, you can provide the database you wish to work with straight on the command line, bypassing the need to use the USE command to choose a database. The following is the syntax for this:

mysql -u [username] -p [database]

To join as the user guest and begin using the tutorial database right away, for instance, you would use:

mysql -u guest -p tutorial

The USE tutorial; command would be issued after connecting without first specifying a database. Alternatively, you can use the -D or –database option to specify the database on the command line.

Using GUI tools like phpMyAdmin

GUI tools make MySQL database interaction easier, especially for non-command line users. Web-based GUI utility phpMyAdmin is popular.

phpMyAdmin lets you administer your MySQL database online. If installed locally, you can access it at http://localhost/phpmyadmin. Web hosting control panels like cPanel include phpMyAdmin.

phpMyAdmin has two main database interfaces:

  1. Using the graphical interface: phpMyAdmin’s menus and dialogs allow users to create and drop databases and tables, manage users and permissions, insert, update, delete, and retrieve records, and import/export data. Through the UI, users can manage their database.
  2. Writing SQL commands: phpMyAdmin further comes with a SQL query window that allows you to directly type and run SQL statements. In a web-based setting, this enables users to take advantage of their SQL expertise.

With its many features for personalizing a database administration system, phpMyAdmin is regarded as a highly strong tool.

Using PHP to connect to MySQL

MySQL is commonly used in conjunction with scripting languages such as PHP to create dynamic web applications. PHP offers tools for connecting to MySQL databases and working with their data.

MySQLi (Improved MySQL) and PDO (PHP Data Objects) are the suggested extensions for PHP versions 5 and up that allow for interaction with MySQL. Since 2012, the earlier MySQL extension has been deprecated and is no longer advised. The decision frequently boils down to personal preference or particular project requirements, but both MySQLi and PDO are good choices.

The database name, port number (if not the default), database hostname or IP address, and username and password for the database account you plan to use are required before you can connect using PHP.

Examples of connecting to a MySQL database using PHP and the MySQLi (object-oriented and procedural styles) and PDO extensions are provided below:

MySQLi (Object-oriented Style)

This style uses PHP objects to interact with the database.

<?php
$servername = "localhost";
$username = "your_username"; // Replace with your database username
$password = "your_password"; // Replace with your database password
$dbname = "your_database";   // Replace with your database name
// Create connection
// Specify database name in the constructor parameters
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection for errors
if ($conn->connect_error) { 
  // If connection fails, stop script and show error
  die("Connection failed: " . $conn->connect_error); 
}
echo "Connected successfully to database '$dbname'";
// --- Database operations (e.g., executing queries) would go here ---
// Close the connection
$conn->close(); 
?>

In this code, the $dbname is provided as the fourth parameter to the mysqli constructor, allowing you to connect directly to a specific database58. Error handling is done by checking the $conn->connect_error property.

MySQLi (Procedural Style)

This style uses functions with a mysqli_ prefix.

<?php
$servername = "localhost";
$username = "your_username"; // Replace with your database username
$password = "your_password"; // Replace with your database password
$dbname = "your_database";   // Replace with your database name
// Create connection
// Specify database name in the function parameters
$conn = mysqli_connect($servername, $username, $password, $dbname); 
// Check connection for errors
if (!$conn) { 
  // If connection fails, stop script and show error
  die("Connection failed: " . mysqli_connect_error()); 
}
echo "Connected successfully to database '$dbname'";
// --- Database operations (e.g., executing queries) would go here ---
// Close the connection
mysqli_close($conn); 
?>

Here, the mysqli_connect() function is used, with $dbname as the fourth argument59. Error checking is performed by evaluating if the returned connection link identifier $conn is false.

PDO (PHP Data Objects)

PDO provides a database-agnostic abstraction layer.

<?php
$servername = "localhost";
$username = "your_username"; // Replace with your database username
$password = "your_password"; // Replace with your database password
$dbname = "your_database";   // Replace with your database name
try {
  // Create connection using a Data Source Name (DSN) string
  // The database name is included in the DSN string
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); 
  // Set the PDO error mode to exception (optional but recommended)
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
  echo "Connected successfully to database '$dbname'";
  // --- Database operations (e.g., executing queries) would go here ---
} catch(PDOException $e) {
  // If connection fails (PDO throws an exception), stop script and show error
  die("Connection failed: " . $e->getMessage()); 
}
// Close the connection by setting the connection variable to null
// PHP's garbage collection often handles this automatically when the script ends.
$conn = null; 
?>

PDO handles connection errors by throwing a PDOException upon failure and employing a try…catch block. When the DSN string is provided to the PDO constructor, the database name ($dbname) is included. The DSN string must contain a valid database in order for PDO to function; otherwise, an error is raised.

Before doing any database actions, the connection must be established in each of these PHP examples. Database connection resources are released when the connection is closed (close() method, mysqli_close() function, or setting the value to null). Late PHP versions deprecated mysql_connect() and mysql_select_db().

It is also available in PHP MySQL: Connect To A Database Using MySQLi And PDO

Command line, GUI, and scripting languages allow users and applications to interface with MySQL databases and meet varied demands and technical levels.

Index