PHP User defined function for connecting to MySqli database[Code Snippet]
The user defined function for the MySqli database connectivity
/* Function For Database Connection */
define ('db_host', 'localhost');
define ('db_name', 'plantmangement');
define ('db_user', 'root');
define ('db_pass', '123');
/**
*Database Connect
*/
function db_connect($host = db_host, $username = db_user, $password = db_pass, $database = db_name) {
if(!$con = mysqli_connect($host, $username, $password,$database)) {
return FALSE;
}
if((strlen($database) > 0) AND (!mysqli_select_db($con,$database))) {
return FALSE;
}
// set the correct charset encoding
mysqli_query($con,'SET NAMES \'utf8\'');
mysqli_query($con,'SET CHARACTER_SET \'utf8\'');
return $con;
}
The client code when we call the db_connect() function from anywhere in our project
if(!$conn = db_connect()) {
die('cant connect to mysql');
}
$sql="Select * from maintenance_plan ORDER BY planned_date ASC";
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo $rowcount;
// Free result set
mysqli_free_result($result);
}
mysqli_close($conn);