How to connect to Database:


Here we will know about the database connectivity on PHP.

Firstly we have to check database credential of the server,

Usually They are as following:
For Local Server (i.e. XAMPP/ WAMPP etc.)
Server: localhost
Username: root
Password:   (blank)
For Server  (i.e. cpanel, window etc)
Server: localhost  or domain name of the website
Username: can be created by Hosting panel using Database wizard (Cpanel) or Option proided on the same
Password:  same as above

We have to create a database to connect with a particular database for a particular  website or Program.

Now we will define all on a variable:
<?php
$databaseserver = "localhost";   // can be changed as required
$databaseuser =  "dbadmin";   // as exapmle I have taken it dbadmin
$databasepassword = "W3help@123";  // as exapmle,  use password as strong, use Capital, small, Number and special Character. Probability of such password guessing is less
$databasename = "wehlpdatabase";   //  can be changed as required
?>
I am describing two ways for running database query from PHP

###    One Way  ###
<?php
// database connection
$dbLink = new mysqli($databaseserver ,$databaseuser ,$databasepassword ,$databasename );
if (!@$dbLink)  { echo "OOPPS.......<br/> something went wrong"; }
// database connection

// create query
$sql  = "select * from table";   // change the query as required
// create query

// sql run
$result = $dbLink->query($sql);
// sql run

// for no results
if($result->num_rows == 0)  {  
// for no results
// write code for no results here
// for no results
} else {  while($row = $result->fetch_assoc()) {  
// for getting every result
/* 
write code here for results
$row is a array for results with index attribute of database's table 
for example id is a attribute of any table
you can echo it using  $row['id'];
*/
// for getting every result
}  // while loop end
}  // else part of no resulta
?>
###    One Way  ###

###  Another way  ###
<?php
mysql_connect($databaseserver ,$databaseuser ,$databasepassword ,$databasename);
// checking the connection
if (mysql_connect_errno())
  {
  echo "OOPPS.......<br/> something went wrong";
  }

$result = mysql_query("select * from table");   // run query in server
$numrow = mysql_num_rows($result);  // check how much row in results
if($numrow>0)  { while($row = mysql_fetch_array($result))   {  // while loop
// for getting every result
/* 
write code here for results
$row is a array for results with index attribute of database's table 
for example id is a attribute of any table
you can echo it using  $row['id'];
*/
// for getting every result
 }  // while loop 
} else {
// no results code here
// code for no results
// no results code here
}

?>
###  Another way  ###

Post a Comment

 
Top