In this article we will show you the solution of how to connect database in PHP, a database is a grouping of connected data. Cross-platform Apache, MySQL, PHP, and Perl, or XAMPP, is an acronym. One of the straightforward, lightweight local servers for website building.
Using the XAMPP web server and PHP, the following path can be used to connect to the database."localhost/phpmyadmin".
Requirements: XAMPP web server procedure:
- Apache and MySQL should be started before the XAMPP server.
- Create a PHP connection script for XAMPP.
- Open the local browser and run it.
- A database based on PHP code has been successfully established.
PHP mysqli_close() function is used to disconnect with MySQL databases. It returns true if the connection is closed or false.
Understanding how to connect to MySQL using PHP script can be useful if you are just starting out in website building.
You can manage, inspect, or alter the tables created in the MySQL database in this way. We will now discuss the idea of how to connect database in php with example.
Step By Step Guide On How To Connect Database In PHP :-
<?php $servername = "localhost"; $username = "root"; $password = ""; $conn = new mysqli($servername, $username, $password); if ($conn->connect_error) { die("Connection failure: " . $conn->connect_error); } $sql = "CREATE DATABASE talkersdata"; if ($conn->query($sql) === TRUE) { echo "Database with name talkersdata"; } else { echo "Error: " . $conn->error; } $conn->close(); ?>
- We start by defining the server name as "localhost", since we are connecting to a local database.
- We then set the username as "root", which is the default username for the PHPMyAdmin database software.
- Since we are not setting a password for the database, we leave the password field as an empty string.
- We create a new mysqli connection using the server name, username, and password that we just defined.
- We check the connection to see if it is successful.In the event that the connection drops, we output an error message and end the script.
- The SQL command "CREATE DATABASE" is used to establish a new database with the name "talkersdata".
- We check if the database creation was successful. If it was, we print a message that the database was created successfully.Otherwise, a message is printed in error.
- We then cut off the database connection.
Conclusion :-
As a result, we have successfully learned how to connect database in php.
You may wish to use multiple MySQL databases in your PHP project, you must define separate connection variables for each database and use variables based on which database is being used for the operation you are performing.
I hope this article on how to connect database in PHP helps you and the steps and method mentioned above are easy to follow and implement.