PHP MySQL Connect to a Database
The free MySQL database is very often used with PHP.
Before you can access and work with data in a database, you must create a connection to the database.
In PHP, this is done with the following commands:
5
mysqli_ssl_set(
$conn
, NULL, NULL,
"DigiCertGlobalRootCA.crt.pem"
, NULL, NULL );
8
mysqli_real_connect(
$conn
,
$host
,
$username
,
$password
,
$database
, 3306 );
mysqli_init ( )
function initializes MySQLi and returns an object to use with the mysqli_real_connect ( )
function.
mysqli_ssl_set ( )
function is used to establish secure connections using SSL (Secure Sockets Layer) where
☂ A PEM file is a text-based file that contains a certificate, a private key, and any associated certificates.
The file DigiCertGlobalRootCA.crt.pem
can be found from here .
mysqli_real_connect ( )
function opens a new connection to the MySQL server.
Parameter
Description
hostname
Specifies the server to connect to.
username
Specifies the username to log in with.
password
Specifies the password to log in with.
schema
Specifies the database to use.
There are more available parameters, but the ones listed above are the most important.
The example below performs the following tasks:
Stores the connection in an object ($conn
) for later use in the script.
The die
part will be executed if the connection fails.
The connection will be closed as soon as the script ends.
To close the connection before, use the mysqli_close ( )
function.
<html><body>
<?php
$host = "undcemmysql.mysql.database.azure.com";
$username = "user_id";
$password = " ";
$database = "schema";
// Initialize MySQLi.
$conn = mysqli_init( );
// Create an SSL connection.
mysqli_ssl_set( $conn, NULL, NULL, "DigiCertGlobalRootCA.crt.pem", NULL, NULL );
// Open a new connection to the MySQL server.
mysqli_real_connect( $conn, $host, $username, $password, $database, 3306 );
// If fail to connect to the database
if ( mysqli_connect_errno( ) )
die( 'Failed to connect to MySQL: ' . mysqli_connect_error( ) );
else
echo "Successfully connect to MySQL!";
// Close the connection.
mysqli_close( $conn );
?>
</body></html>