PHP database connection


php PHP database connection PHP Connection

How to connect mysql database in PHP ?

To perform database operations like insert, read, update, delete operations we need the database connection.

1- PHP Database connection using mysql function

To connect the database using PHP mysql function we will use the two PHP functions. 1- mysql_connect() with three following server related parameters. • Server name • Username assigned to database • Password mysql_connect('ServerName','Username','Password'); 2- mysql_select_db() with one parameter. • Database name mysql_select_db('DatabaseName') For localhost WAMP/XAMPP etc the default username is 'root' and no password. PHP Database connection using mysql function Database Name ⇨ myfirstdatabase <?php mysql_connect('localhost', 'root', ''); mysql_select_db('myfirstdatabase'); ?> You can establish the database connection using above simple code.

2- PHP Database connection using mysqli function

mysqli_connect('ServerName', 'Username', 'Password', 'DatabaseName');For mysqli function we have to pass all four parameters into the mysqli_connect() function. Database Name ⇨ myfirstdatabase <?php $conn = mysqli_connect('localhost', 'root', '', 'myfirstdatabase'); ?>

Advantages of PHP mysqli functions

We can include more than one different connection of database into the single PHP page. For example . There are two following database users. • USERA • USERB For USERA we don't want that he should have access to update the database, and for USERB we want to set that he should have all database's operations access. So in this case we can make two connection within the same PHP file. Note. We can set the user access setting or privileges setting from database setting in Phpmyadmin.

<?php $usera_connection = mysqli_connect('localhost', 'usera','12345', 'myfirstdatabase'); $userb_connection = mysqli_connect('localhost', 'userb','12345', 'myfirstdatabase'); ?>
php PHP Connection Chapter Next »