insert data into database php code example

Example 1: php insert and display data

<?php
//including the database connection file
include("config.php");
if(isset($_POST['Submit'])) {    
$pname = $_POST['pname'];
$pcode = $_POST['pcode'];
$pprice = $_POST['pprice'];
        
// checking empty fields
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>";
}
//link to the previous page
 echo "<br><a href="javascript:self.history.back();">Go Back</a>";
 } else { 
// if all the fields are filled (not empty)             
//insert data to database
$result = mysqli_query($cser, "INSERT INTO crud2(pname,pcode,pprice) VALUES('$pname','$pcode','$pprice')");
        
//display success message
echo "<font color="green">Data added successfully.</font>";
        
}
}
?>

Example 2: insert php code

<?php
$host = "localhost";
$username = "username";
$pass = "";
$db="furniture";


// Create connection
$conn=mysqli_connect($host,$username,$pass,$db);

if(!$conn){
  die("Data connection error");
}
?>

Example 3: how to insert data from a from in html to phpmyadmin using php

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form - PHP/MySQL Demo Code</title>
</head>

<body>
<fieldset>
<legend>Contact Form</legend>
<form name="frmContact" method="post" action="contact.php">
<p>
<label for="Name">Name </label>
<input type="text" name="txtName" id="txtName">
</p>
<p>
<label for="email">Email</label>
<input type="text" name="txtEmail" id="txtEmail">
</p>
<p>
<label for="phone">Phone</label>
<input type="text" name="txtPhone" id="txtPhone">
</p>
<p>
<label for="message">Message</label>
<textarea name="txtMessage" id="txtMessage"></textarea>
</p>
<p> </p>
<p>
<input type="submit" name="Submit" id="Submit" value="Submit">
</p>
</form>
</fieldset>
</body>
</html>

Tags:

Sql Example