In this section, you will learn how to connect to MySQL Server using MySQL command-line and PHP. 

 

How connect to the MySQL server from the command?

To connect to the MySQL Server, you use this command:

 

shell>mysql -u root -p

-u root means that you connect to the MySQL Server using the user account root.

-p instructs MySQL to prompt for a password.

 

You type the password for the user account root and press Enter:

Enter password: ********

 

 

MySQL Connection Using PHP

PHP 5 and later will work with a MySQL database using: MySQLi extension (the "i" stands for improved) PDO (PHP knowledge Objects).

 

Example (MySQLi Object-Oriented)

 

Try the following example to connect to a MySQL server in MySQLi Object-Oriented way.

 

<?php

//Your MySQL databse settings
$servername = "localhost";
$username = "root";
$password = "root";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

?>

 

 

Example (MySQLi Procedural)

 

Try the following example to connect to a MySQL server in MySQLi Procedural way.

 

<?php

//Your MySQL databse settings
$servername = "localhost";
$username = "root";
$password = "root";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

?>

 

 

Example (PDO)

Try the following example to connect to a MySQL server in MySQLi PDO way.

 

<?php

//Your MySQL database settings
$servername = "localhost";
$username = "root";
$password = "root";
$database = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}

?> 

 

 

Close the Connection

The connection can be closed by using the following PHP functions.

 

<?php

//MySQLi Object-Oriented
$conn->close();

//MySQLi Procedural
mysqli_close($conn);

//PDO
$conn = null;

?>

 

 

What is Next?

 

In the next section, you will learn how to create a database in MySQL.

 

About Tec News

Tec News is optimized for learning Web Development, Programming, Database System and Tutorials, Articles, References for your development. This web help developers, learners learn these technologies easy and free.

Contact Us

If you have any suggestions or have any questions regarding our web please feel free to contact us.

info@tec-news.com        

https://www.tec-news.com