In this post, you will be learning about how to insert data into database in php mysql using oops concept. So, we will be using bootstrap 5 for designing the html form user interface.
dbcon.php
<?php
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_DATABASE','oops');
class DatabaseConnection
{
public function __construct()
{
$conn = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);
if($conn->connect_error)
{
die ("<h1>Database Connection Failed</h1>");
}
//echo "Database Connected Successfully";
return $this->conn = $conn;
}
}
?>
dbcon.php
<?php
class database{
private $host;
private $db;
private $username;
private $pw;
protected function connect(){
$this->host = 'localhost';
$this->db = 'oops';
$this->username = 'root';
$this->pw = '';
$con = new mysqli($this->host, $this->username, $this->pw, $this->db);
return $con;
}
}
?>
index.php
<div class="container mt-4">
<div class="row">
<div class="col-md-12">
<?php
if(isset($_SESSION['message']))
{
echo "<h5>".$_SESSION['message']."</h5>";
unset($_SESSION['message']);
}
?>
<div class="card">
<div class="card-header">
<h4>Student Add</h4>
</div>
<div class="card-body">
<form action="submit.php" method="POST">
<div class="mb-3">
<label for="">Full Name</label>
<input type="text" name="name" required class="form-control" />
</div>
<div class="mb-3">
<label for="">Email ID</label>
<input type="text" name="email" required class="form-control" />
</div>
<div class="mb-3">
<label for="">Phone</label>
<input type="text" name="phone" required class="form-control" />
</div>
<div class="mb-3">
<button type="submit" name="save_student" class="btn btn-primary">Save Student</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
submit.php
<?php
include 'dbcon.php';
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
class query extends database{
function insert($name, $email, $phone){
$q = "INSERT INTO student (name, email, phone) VALUES ('$name', '$email', '$phone')";
$result = $this->connect()->query($q);
if($result)
{
$_SESSION['message'] = "Student Added Successfully";
header("Location: index.php");
exit(0);
}
else
{
$_SESSION['message'] = "Not Inserted";
header("Location: index.php");
exit(0);
}
}
}
$obj = new query;
$obj->insert($name, $email, $phone);
?>