Insert Data Example in PHP

Connect MySql Database

<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database"; // Create connection $conn = new mysqli($servername, $username, $password,$dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>

Insert Data Using MySQL

$sql = "INSERT INTO students (student_name, student_email, student_city) VALUES ('John', 'john@example.com','los angeles')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; }$conn->close();


To create database and table

//First create database CREATE DATABASE 'college'; //Then create table CREATE TABLE 'students' ( 'student_id' int(11) NOT NULL AUTO_INCREMENT, 'student_name' varchar(255) NOT NULL, 'student_email' varchar(255) NOT NULL, 'student_city' varchar(255) NOT NULL, PRIMARY KEY ('student_id') )

Php File : view.php

<html> <head> <title>insert data in database using mysqli</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div id="main"> <h1>Insert data into database using mysqli</h1> <div id="login"> <h2>Student's Form</h2> <hr/> <form action="" method="post"> <label>Student Name :</label> <input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br /> <label>Student Email :</label> <input type="email" name="stu_email" id="email" required="required" placeholder="john123@gmail.com"/><br/><br /> <label>Student City :</label> <input type="text" name="stu_city" id="city" required="required" placeholder="Please Enter Your City"/><br/><br /> <input type="submit" value=" Submit " name="submit"/><br /> </form> </div> <!-- Right side div --> <div id="formget"> <a href=https://www.formget.com/app><img src="formget.jpg" alt="Online Form Builder"/></a> </div> </div> <?php if(isset($_POST["submit"])){ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "college"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO students (student_name, student_email, student_city) VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')"; if ($conn->query($sql) === TRUE) { echo "<script type= 'text/javascript'>alert('New record created successfully');</script>"; } else { echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>"; } $conn->close(); } ?> </body> </html>


Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment