Connecting To Database (MySQL) in PHP
Connecting To Database (MySQL) in PHP
in PHP
Create a Connection with DB:
• By using PHP,we can able to connect with database(MySQL).
• In order to connect with database, we need three parameters
Hostname(ServerName) (By default “localhost”)
Username (By default “root”)
Password (By default “No Password”)
• In PHP, we have one inbuilt function to create connection with database(MySQL)
.i.e.,
– mysqli_connect(hostname,username,password)
• This function creates a successful connection with DB if you provide valid
information.
• When the connection is not well we can kill that connection by using
– die(“Can’t create connection”);
• mysqli_close() function is used to disconnect with MySQL database.
Example:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>
Execute Queries:
Create a Database:
• After creating connection we need to create a database .
• PHP has one in built function to perform different operations
(create (db &table),insert,update and delete) on database.i.e.,
– mysqli_query(connection,query)
• It has two parameters, those are
– Connection :name of the connection
– Query: specifies the query
Example:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$sql = 'CREATE DATABASE CollegeDb';
if(mysqli_query( $conn,$sql))
{
echo "Database created successfully.";
}
else
{
echo "Sorry, database creation failed ".mysqli_error($conn);
}
mysqli_close($conn);
?>
Creating a Table
• After creating database, we need to create
table.
• In PHP, mysqli_query() function is used to
create a table.
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname='CollegeDb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo "Connected successfully <br/>“;
$sql = "create table students(Sid INT,Sname VARCHAR(20),Age INT)";
if(mysqli_query($conn, $sql)){
echo "Table students created successfully";
}else{
echo "Could not create table: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
Insert Record into Table
if(mysqli_num_rows($retval) > 0)
{
while($row = mysqli_fetch_assoc($retval))
{
echo "Student ID :".$row['sid']."<br> ";
echo "Student NAME :". $row['sname']."<br> ";
echo "Student Age :". $row['age']." <br> ";
echo "--------------------------------<br>";
} //end of while
}
else
{
echo "0 results";
}
mysqli_close($conn);