How can I open a database connection in user class , where I can do database operation? and why need to define inbuilt created functions in DBConnection class ..????
I have created
- db.php
- user.php
- result.php
in db.php
class DBConnection
{
protected $mysqli;
private $db_host="127.0.0.1";
private $db_name="test";
private $db_username="root";
private $db_password="";
public function __construct()
{
$this->mysqli=new mysqli($this->db_host,$this->db_username,
$this-> db_password,$this->db_name) or die($this->mysqli->error);
return $this->mysqli;
}
public function query($query) // why i need to creat this function
{
return $this->mysqli->query($query);
}
public function real_escape_string($str)
{
return $this->mysqli->real_escape_string();
}
function __destruct(){
//Close the Connection
$this->mysqli->close();
}
}
?>
in User.php
<?php
require "db.php";
class User {
public function __construct($conn)
{
$this->mysqli=$conn;
}
public function addUser($name,$username,$email,$pwd)
{
$query=" ";
$res=$this->mysqli->query($query);
//pls chek the query function in DBConnection,what is the need to define query > function in DBConnection ?
return $res;
}
}
?>
in result.php
<?php
require "user.php";
$conn=new DBConnection();
if(isset($_POST['submit']))
{
$name = $conn->real_escape_string(trim(strip_tags($_POST['name']))); $username = $conn->real_escape_string(trim(strip_tags($_POST['username']))); $email = $conn->real_escape_string(trim(strip_tags($_POST['email']))); $password = $conn->real_escape_string(trim(strip_tags($_POST['pass'])));
//echo $name."".$username."".$email."".$password;
$uObj=new User($conn);
$uObj->addUser($name,$username,$email,$password);
echo " hi your name is <I>".$name."</I> and your email ID is <I>".$email."</I>";
}
?>
See Question&Answers more detail:os