Php mysql connection example

Before we start building database driven php application, we must learn how to connect to any database from php web application. (Note, here in example we connect mysql database, but you can connect to any other database just by changing the provider).

Php mysql database connection example: Here we see how to create php to mysql database connection in our local environment, because this is what you always require while developing any php application.

Php mysql database connection

To connect any database, we need to know four properties of database, like database name, user name, password, database location, and the provider type.

We can connect mysql database using different php component.

Php MySql using mysql improved extension

Please replace username, password, and dbname with your username, password and database name.

In place of localhost you can specify any server name or IP address where the database is located

<?php
    $mysqli = new mysqli("localhost", "username", "password", "dbname");
?>

After connection you can use that above $mysqli variable to read data from database.

<?php
$result = $mysqli->query("SELECT ColumnName1 FROM TableName");
?>
PHP Data Objects: Connecting to mysql using PDO

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases

<?php
    $myPDO = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');
?>

replace username, password, and dbname with your username, password and database name.

After connection you can use that above $myPDO variable to read data from database.

<?php
$result =$myPDO->query("SELECT ColumnName1 FROM TableName");
?>

If you are connecting remote mysql database using php

<?php
$mysqli = new mysqli("db.hostingserver.com", 
"username", "password", "dbname"); ?>

In case you are using encrypted connection string please make sure you are using the same key for decryption

Reading from configuration file

Instead of keeping username and password in your php code, you also can store information in configuration file and then read information from there, ideally that would be the best way of writing code.

$db = mysqli_connect(ini_get("mysql.default.user"), ini_get("mysql.default.password"), ini_get("mysql.default.host"));

While working with any database from php application, you may come across different errors, to deal with them must learn how to know php errors handling best practices.

 
PHP MySQL Connection
Learn php programming, php web development with free tutorials
Other Popular Tutorials
PHP Examples | Join PHP Online Course