Lab 2 PHP Connect to DB

db_connect.php

<?php
/**
* A class file to connect to database
*/
class DB_CONNECT { 
    
    var $myconn;
/* Function to connect with the database*/ 


function connect() {

define('DB_USER', "root");             // db user
define('DB_PASSWORD', "");            // db password (default is empty) 
define('DB_DATABASE', "mydatabase");  // database name 
define('DB_SERVER', "localhost");     // db server


// Connecting to mysql database

$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE) or die(mysqli_error($con));
$this->myconn = $con;



// returning connection cursor 

return  $this->myconn;



}
/* Function to close db connection */


function close($myconn) {
// closing db connection 
   mysqli_close($myconn);


}
}
?>

useDBConnect.php

<?php

// include db_connect.php file
require_once __DIR__ . '/db_connect.php';



//check if connect button is set and submitted 

if(isset($_POST["submit"])) {
// create a new instance of DB_CONNECT class
$db= new DB_CONNECT();
//call the function connect() in DB_CONNECT class
$connection = $db->connect();


if (!$connection)  //if no connection echo "Connection failed"
echo("Connection failed"); else echo "Connected successfully"; } ?>
<h2> SQL Database Connection </h2>
<form action="useDBConnect.php" method="post">
<input type="submit" name="submit" value="Connect">
</form>

   Use   useDBConnect.php to test out if you could connect to the database name mydatabase

   if u click connect and see connected successfully means your code is written correctly for db_connect.php












 



Comments

Popular posts from this blog

Simple Login Example (PHP Server + Android Client)

Lab 6: Using split