Insert data
using function
First , We are going to create a class
for database connection. This class has two main methods , one is connect which
contains connectivity code with PHP and MYSQL.
Another method is saveRecord() . It has
one mandatory argument that is first argument(database table name) and another
arguments are data inputted by users using html form.
Example :
1. Database Connection Class:
<?php
class
Database
{
public $conn;
var $dbhost = 'localhost';
var $dbuser = 'root';
var $dbpass = '';
var $dbase = 'usermanagementsystem';
public function __construct() {
$this->conn =
mysqli_connect($this->dbhost, $this->dbuser, $this->dbpass,
$this->dbase);
if (!$this->conn) {
die('failed' . mysqli_error());
} else {
// echo 'done';
}
}
public function insert($table_name,
$data) //member function
{
$string = "INSERT INTO
".$table_name." (";
$string .= implode(",",
array_keys($data)) . ') VALUES (';
$string .= "'" .
implode("','", array_values($data)) . "')";
if(mysqli_query($this->conn,
$string))
{
echo "inserted";
}
else
{
echo
mysqli_error($this->con);
}
} }
?>
2. HTML Form
<?php
include
'database.php';
$data = new
Database;
if(isset($_POST["submit"]))
{
$insert_data =
array(
'fname' =>
mysqli_real_escape_string($data->conn, $_POST['fname']),
'age' => mysqli_real_escape_string($data->conn, $_POST['age'])
);
if($data->insert('demo', $insert_data))
{
//echo
"inserted";
}
}
?>
<html>
<head>
<title>Registration Form</title>
<link rel="stylesheet"
href="css/style.css" type="text/css">
</head>
<body>
<center>
<form action="" method="POST">
<input type="text" name="fname"
placeholder="First name"/><br>
<input type="number" name="age"
placeholder="Enter age"/><br>
<input type="submit" value="submit"
name="submit" class="btn"/>
</form>
</center>
</body>
</html>
So, this
way we can insert data using function.
Comments
Post a Comment