Connect MySQL Database with PHP Source Code and Command Line

In this article, You will learn how to connect mysql using command line (CMD) and php source code.

How to connect to MySQL Database using Command Line and PHP Script/Code?

Here are ways:

  • MySQL Connect Using Command Line
  • PHP Database Connection with MySQL

MySQL Connect Using Command Line

Steps to connect MySQL from using command line:

1. Log in to your Hosting account using SSH

On the command line, write the following command, replace USERNAME to your USERNAME :-

mysql -u USERNAME -p

2. Enter Password

At the password prompt, type your password. When you type the correct password, mysql> prompts are displayed.

3. To See List of Database

To display a list of databases, Use the below command at the mysql> prompt :-

show databases;

4. Use Database

To access a specific database, use the following command at the mysql> prompt, and also replace the DBNAME with the database you your database name :-

use DBNAME;

5. Accessed Database

After accessing the database, you can run SQL queries, list tables and so on. apart from this :-

  • To see a list of MySQL commands, type help at mysql> prompt.
  • To exit the Mysql program, type \ q at mysql> prompt.

PHP Database Connection with MySQL

PHP provides mysql_connect() function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success or FALSE on failure.

Syntax

mysql_connect(host,username,password,new_link,client_flag);

Here is source code to connect MySQL database with php:

<?php
$host= "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($host, $username, $password);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>

Recommended Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *