11.6 C
Jaipur
Wednesday, December 8, 2021

What is connection string in MySQL

Must read

In this article, we will learn how we can access the data from the MySQL database using the PHP language.

What is MySQL connection string

Connection string is a string that specifies the information related to database login. For understanding, we will consider an example of a PHP scripting language and will write a code to establish the connection with the database. We have a database, named “Organization”, the user name is “maadi” and password is “qwer1234”:

<?php
//Establishment of Connection with database
$connection = mysqli_connect(“localhost”,“maadi”,“qwer1234”,“Organization”);
//checking status of connection
if (mysqli_connect_errno()) {
     echo “Failed to connect to MySQL: “ .mysqli_connect_error();
     echo  n;
     exit();
     }
else {
echo  “Connection Successfuln;
     exit();
}
mysqli_close($connection);
?>

In PHP, we have different MySQL built-in functions which make our task easy, like we have a connection string known as “mysqli_connect” which is used to connect the database. The general syntax of the mysqli_connect() function is:

[Variable_name (in which results to be stored)] = mysqli_connect ([host],[user_name],[password],[database_name]);

In our code, this statement is used as:

$connection = mysqli_connect(“localhost”,“maadi”,“qwer1234”,“Organization”);

Then we have another built-in function, mysqli_connect_errno(), which is used to return the error if the connection failed with the database and in the last, we use another built-in function, mysqli_close() which is used to close the connection. For more understanding, we will run the following code which is stored in a file, named, file.php:

Open the terminal and type:

Our connection with the database is connected successfully as the output is displaying. Now we will enter the wrong password and will execute the code again:

<?php
//Establishment of Connection with database
$connection = mysqli_connect(“localhost”,“maadi”,“qwer12”,“Organization”);
//checking status of connection
if (mysqli_connect_errno()) {
     echo “Failed to connect to MySQL: “ .mysqli_connect_error();
     echo  n;
     exit();
     }
else {
echo  “Connection Successfuln;
     exit();
}
mysqli_close($connection);
?>

The file is as:

Again run the command in a terminal:

The output generated the error of the password.

Conclusion

The MySQL connection string is used to open a new connection with the MySQL database, by using different parameters and is used in different scripting languages like PHP, Python, and C language. The PHP language is used a lot nowadays in backend development so we have discussed in this article the use of MySQL connection string with the help of a PHP language code.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisement -

Latest article