Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

PHP Database connection

  • Difficulty Level : Easy
  • Last Updated : 02 Nov, 2020

The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development.

Requirements: XAMPP web server procedure:

  • Start XAMPP server by starting Apache and MySQL.
  • Write PHP script for connecting to XAMPP.
  • Run it in the local browser.
  • Database is successfully created which is based on the PHP code.

In PHP, we can connect to the database using XAMPP web server by using the following path.

"localhost/phpmyadmin"

Steps in Detail:

  • Open XAMPP and start running Apache, MySQL and FileZilla
  • Now open your PHP file and write your PHP code to create database and a table in your database.

    PHP code to create a database:



    PHP




    <?php
      
    // Server name must be localhost
    $servername = "localhost";
      
    // In my case, user name will be root
    $username = "root";
      
    // Password is empty
    $password = "";
      
    // Creating a connection
    $conn = new mysqli($servername
                $username, $password);
      
    // Check connection
    if ($conn->connect_error) {
        die("Connection failure: " 
            . $conn->connect_error);
      
    // Creating a database named geekdata
    $sql = "CREATE DATABASE geekdata";
    if ($conn->query($sql) === TRUE) {
        echo "Database with name geekdata";
    } else {
        echo "Error: " . $conn->error;
    }
      
    // Closing connection
    $conn->close();
    ?>
  • Save the file as “data.php” in htdocs folder under XAMPP folder.
  • Then open your web browser and type localhost/data.php

Finally the database is created and connected to PHP.

If you want to see your database, just type localhost/phpmyadmin in the web browser and the database can be found.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!