PHP MySQL Insert Data
Insert Data Into MySQL Using MySQLi and PDO
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
- The SQL query must be quoted in PHP
- String values inside the SQL query must be quoted
- Numeric values must not be quoted
- The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)In the previous chapter we created an empty table named "MyGuests" with five columns: "id", "firstname", "lastname", "email" and "reg_date". Now, let us fill the table with data.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Database Connection: The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. In PHP, we can connect to database using localhost XAMPP web server.
Complete Steps to Design Project:
- Start XAMPP Server.
- Open localhost/phpmyadmin in your web browser.
- Create database of name staff and table of name college.
- Write HTML and PHP code in your Notepad in a particular folder.
- Submit data through HTML Form.
- Verify the results.
Steps In detail:
- Start XAMPP Server by opening XAMPP and click on XAMPP Start.

- Open localhost/phpmyadmin in your web browser and create database with database name as staff and click on create.

- Then create table name college.

- Enter columns and click on save

- Now open Notepad and start writing PHP code and save it as index.php and open other notepad and save it as insert.php Save both files in one folder under htdocs.

Filename: index.php
- PHP
Filename: insert.php
- PHP
Output: Type localhost/7058/index.php in your browser, it will display the form. After submitting the form, the form data is submitted into database.



Let’s check in our database
