How to give database connection in PHP MySQL

How to give or make a database connection in PHP MySQL


In this post, you will be learning how to create or give a database connection in php mysql.

So guys, first you will have to create a database in phpMyAdmin (Server) and then get your hostname, database name, username and password.

But, If we are using in our system, xampp or wampp server, then by default it would be like: host="localhost", database_name="your_create_db", username="root" & password=" ". Example given below:

Example (MySQLi Object-Oriented)
<?php
    $host = "localhost";
    $username = "your_username";
    $password = "your_password";
    $database = "your_database_name";

    // Create DB Connection
    $conn = new mysqli($host, $username, $password, $database);

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

    echo "Database Connected successfully";
?>


Example in (MySQLi Procedural)
<?php
    $host = "localhost";
    $username = "your_username";
    $password = "your_password";
    $database = "your_database_name";

    // Create DB Connection
    $conn = mysqli_connect($host, $username, $password, $database);

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


Thanks for reading.

© Copyright - 2018 - 2022 | All rights reserved at Funda of Web IT