Database connection using PHP MySqli

For PHP freshers, one important thing is mysql_* functions are deprecated. Instead of mysql_* functions now we use mysqli_* functions.

PHP mysqli_connect() Function is used for connection to mysql database.




Example
Open a new connection to the MySQL server:

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>


If we are using wamp or xamp on localhost,
my_user = root

my_password = "" (blank/empty)
my_db = your database name


This function returns an object representing the connection to the MySQL server, the returned connection object is used for executing mysql queries.


Insert Data Into MySQL Using MySQLi:
The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Example:
The following examples add a new record to the "MyGuests" table:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>


In this way, we just understood the concept and basics of mysqli connection.