how insert data in database using php code example
Example 1: php insert and display data
<?php
include("config.php");
if(isset($_POST['Submit'])) {
$pname = $_POST['pname'];
$pcode = $_POST['pcode'];
$pprice = $_POST['pprice'];
if(empty($pname) || empty($pcode) || empty($pprice)) {
if(empty($pname)) {
echo "<font color="red">Product Name field is empty.</font><br>";
}
if(empty($pcode)) {
echo "<font color="red">Product Code field is empty.</font><br>";
}
if(empty($pprice)) {
echo "<font color="red">Product Price field is empty.</font><br>";
}
echo "<br><a href="javascript:self.history.back();">Go Back</a>";
} else {
$result = mysqli_query($cser, "INSERT INTO crud2(pname,pcode,pprice) VALUES('$pname','$pcode','$pprice')");
echo "<font color="green">Data added successfully.</font>";
}
}
?>
Example 2: insert php code
<?php
$host = "localhost";
$username = "username";
$pass = "";
$db="furniture";
$conn=mysqli_connect($host,$username,$pass,$db);
if(!$conn){
die("Data connection error");
}
?>
Example 3: insert a row from databse using php
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'crud');
$name = "";
$address = "";
$id = 0;
$update = false;
if (isset($_POST['save'])) {
$name = $_POST['name'];
$address = $_POST['address'];
mysqli_query($db, "INSERT INTO info (name, address) VALUES ('$name', '$address')");
$_SESSION['message'] = "Address saved";
header('location: index.php');
}