PHP – MYSQL – Open and Close a connection to the MySQL server

1. Create a Data Base and assign a User

Blue Host users:

CPanel> Database Tools> MySQL databases>
– Create a Database
– Create a User
– Assign User to Database

2. Manage the DB

Blue Host users:

CPanel> phpMyAdmin> Enter with User name and password

LEFT COLUMN> you will see your new empty Database.

A Database is a data structure with tables, every table has rows and columns.

3. Write PHP code

Open a connection, it will be closed automatically when the script ends

<?php
// Create connection
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");

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

Statement: mysqli_connect(host,username,password,dbname);

NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost

To close a connection using script:

<?php
// Create connection
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!";
  }

// Close connection
mysqli_close($con); 
echo "Connection Closed";
?>

NOTICE: PHP function – mysqli_close() –