Ask Question

Menu

MySQLi database Connection in PHP


MySQLi is the improve version of MySQL.The "i" stands for improved.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Example

<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$database = "mydb";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

"mysqli_connect" function

When web server executed the "mysqli_connect" function, if it execute succesfully then it return value or connection object.

$conn

The return value store in "$conn" or any user defined ( a function provided by the user) variable.

if you don't want to store the database address as variable then the database connection code is

<?php
// Create connection
$conn = mysqli_connect("localhost","root","admin","mydb");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Example

<?php
// Create connection
$conn = mysqli_connect("localhost","root","admin","mydb");
?>

This code also use as database connection but it will not show the output message that it is successfully connect or not.

Here







Subscribe with us to get latest topic update






Choose a Language



Subscribe