Connection to Database
×
Home Courses Community Support
Connection to Database

Before we can access database, we must open a connection to the MySQL server. For PHP MySQL, this is done with the MySQLi_connect() function.

Syntax is ab below:

mysqli_connect(host,username,password,dbname);


Here is the description of parameter of this function -

Host: Name of host where database exist. We can use a host name or an IP address of host.

Username: The MySQL user name to access particular database

Password: The password to log in with.

dbname: The database name which we want to be used when performing queries

 

enlightenedThere are more available parameters, but the parameters listed above are the most important.

 

In the following example we store the connection in a variable ($con) for later use in the script:
 

<html>
<body>
<?php
//creating a connection to database
$con = mysqli_connect("localhost","root","","myweb");
if (mysqli_connect_errno())
echo"Failed to connect to MySQL: ".mysqli_connect_error();
else{
//do all your stuff here
echo "Connected Successfully";
}
mysqli_close($con); //ending the connection to database
?>
</body>
<html>


When you will run below code on your local machine it will return, connected successfully.

 

enlightenedwe have used password blank because I did not set any password for username root on my local machine.

 

Instead of prinitng message we can do any stuff with database. In next heading we will learn how to insert data into database.

 

 

← Preview

Creating a Database

Next →

Insert Data in Database

NOTES

Our mission is to provide highly effective and quality education via innovative solutions. Geeksdemy look forward to bridge the gap between in-demand technology and academics in order to deliver innovative, easy, interesting and affordable learning across the Globe.

Courses

  • Python
  • Game Development with Unity 3D
  • Arduino
  • PCB & Circuit Designing
  • Robotics and Embedded C
  • 8051/8052 Embedded Systems
  • QuadCopter & UAV
  • MATLAB with Robotics
  • Raspberry Pi
Learn On the Go!
Get the Android App
Get the iOS App