- Php Insert Form Data Into Mysql Database Using MySQLI Code.
- PHP MySQL Insert Data
- Example (MySQLi Object-oriented)
- Example (MySQLi Procedural)
- Example (PDO)
- Insert Input values into database using PHP
- Create the Database
- Add a table
- Create the WebForm
- A simple Pizza Order Form
- Please enter customer's order
- Order Details
- Insert Input values into database using PHP
- Create the Database
- Add a table
- Create the WebForm
- A simple Pizza Order Form
- Please enter customer's order
- Order Details
- How to Insert Select Option Value in Database Using PHP & MySQL
- How to Store Dropdown Value in Database in PHP
- 1. Create SQL Database & Table
- 2. Connect PHP to MySQL
- 3. Create Input Field for Select Option
- 4. Insert Select Option in Database
- Insert Select Option Value with another Input Value using PHP & MySQL
- Create a form and display select option values
- Insert Select Option value & Text Input Value
Php Insert Form Data Into Mysql Database Using MySQLI Code.
________________________________________________________
In this Php Tutorial we will Learn How To Insert Data Into MySQL Database Table From Form Inputs In Php using MySQLI .
I Use In This Tutorial:
— NetBeans IDE .
— XAMPP .
— PhpMyAdmin .
// php code to Insert data into mysql database from input text
if(isset($_POST[‘insert’]))
$hostname = «localhost»;
$username = «root»;
$password = «»;
$databaseName = «test_db»;
// get values form input text and number
$fname = $_POST[‘fname’];
$lname = $_POST[‘lname’];
$age = $_POST[‘age’];
// connect to mysql database using mysqli
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// mysql query to insert data
$query = «INSERT INTO `users`(`fname`, `lname`, `age`) VALUES (‘$fname’,’$lname’,’$age’)»;
$result = mysqli_query($connect,$query);
// check if mysql query successful
if($result)
echo ‘Data Inserted’;
>
else
echo ‘Data Not Inserted’;
>
mysqli_free_result($result);
mysqli_close($connect);
>
?>
PHP MySQL Insert Data
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:
To learn more about SQL, please visit our SQL tutorial.
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.
Note: If a column is AUTO_INCREMENT (like the «id» column) or TIMESTAMP with default update of current_timesamp (like the «reg_date» column), it is no need to be specified in the SQL query; MySQL will automatically add the value.
The following examples add a new record to the «MyGuests» table:
Example (MySQLi Object-oriented)
$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;
?php
// 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 . «
» . $conn->error;
>
Example (MySQLi Procedural)
$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;
?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;
if (mysqli_query($conn, $sql)) echo «New record created successfully»;
> else echo «Error: » . $sql . «
» . mysqli_error($conn);
>
Example (PDO)
$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDBPDO»;
?php
try $conn = new PDO(«mysql:host=$servername;dbname=$dbname», $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;
// use exec() because no results are returned
$conn->exec($sql);
echo «New record created successfully»;
> catch(PDOException $e) echo $sql . «
» . $e->getMessage();
>
Insert Input values into database using PHP
Tutorials Panel written 1 year ago
In this tutorial, we are going to learn how to get values from the user using a text field, text area, and checkboxes and save the values in the database.
The following is a simple Pizza order form which asks for a customer’s name, address, and extra topics customer would like to have on his/her pizza.
Create the Database
Let’s create a database called ‘pizzacorner’ for the sake of example.
Add a table
Now create the table ‘orders’ with four columns for order id, customer name, delivery address, and extra pizza toppings customer would like to have.
You can use phpMyAdmin or MySQL console to create table ‘orders’.
DROP TABLE IF EXISTS `orders`; CREATE TABLE IF NOT EXISTS `orders` ( `order_id` int(11) NOT NULL AUTO_INCREMENT, `customer` varchar(200) NOT NULL, `address` varchar(250) NOT NULL, `toppings` varchar(250) NOT NULL, PRIMARY KEY (`order_id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
Define order_id as your primary key. Set it as auto_increment so you don’t have to add the value of order_id manually.
Create the WebForm
Create a new php file, and save it as ‘pizzaorder.php’.
Pizzaorder.php will have an html form which would take the order details from the user.
A simple Pizza Order Form
Please enter customer's order
Pepperoni Sausage BBQ Sauce Mushrooms Onions
body #book_form label .msg input[type="submit"] < background: #28d; border-color: transparent; color: #fff; cursor: pointer; padding:7px; width:200px; >.login input[type="submit"]:hover
Create a new file ‘pizzaorder_ac.php’
$query = "insert into orders(customer, address, toppings) values('$customerName', '$customerAddress', '$pizzaToppings')"; $result = mysqli_query($conn, $query) or die("Could not execute query"); if($result) < ?>Order Details
Order has been added successfully!
strip_tags() and htmlspecialchars() are two built-in PHP methods use to sanitize the user’s input.
The implode() is a built-in method that joins array elements and output as a string. Implode(string $glue, array $arr) takes “, “ and $pizzaToppings as input and returns a string where each array value is separated by a comma and space.
Once we have collected user input into variables, we use these to create a query to execute.
If everything is executed fine, the data will be entered into the database and a success message will be displayed. As you can see, the data has been added successfully.
Related Articles
Insert Input values into database using PHP
Tutorials Panel written 1 year ago
In this tutorial, we are going to learn how to get values from the user using a text field, text area, and checkboxes and save the values in the database.
The following is a simple Pizza order form which asks for a customer’s name, address, and extra topics customer would like to have on his/her pizza.
Create the Database
Let’s create a database called ‘pizzacorner’ for the sake of example.
Add a table
Now create the table ‘orders’ with four columns for order id, customer name, delivery address, and extra pizza toppings customer would like to have.
You can use phpMyAdmin or MySQL console to create table ‘orders’.
DROP TABLE IF EXISTS `orders`; CREATE TABLE IF NOT EXISTS `orders` ( `order_id` int(11) NOT NULL AUTO_INCREMENT, `customer` varchar(200) NOT NULL, `address` varchar(250) NOT NULL, `toppings` varchar(250) NOT NULL, PRIMARY KEY (`order_id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
Define order_id as your primary key. Set it as auto_increment so you don’t have to add the value of order_id manually.
Create the WebForm
Create a new php file, and save it as ‘pizzaorder.php’.
Pizzaorder.php will have an html form which would take the order details from the user.
A simple Pizza Order Form
Please enter customer's order
Pepperoni Sausage BBQ Sauce Mushrooms Onions
body #book_form label .msg input[type="submit"] < background: #28d; border-color: transparent; color: #fff; cursor: pointer; padding:7px; width:200px; >.login input[type="submit"]:hover
Create a new file ‘pizzaorder_ac.php’
$query = "insert into orders(customer, address, toppings) values('$customerName', '$customerAddress', '$pizzaToppings')"; $result = mysqli_query($conn, $query) or die("Could not execute query"); if($result) < ?>Order Details
Order has been added successfully!
strip_tags() and htmlspecialchars() are two built-in PHP methods use to sanitize the user’s input.
The implode() is a built-in method that joins array elements and output as a string. Implode(string $glue, array $arr) takes “, “ and $pizzaToppings as input and returns a string where each array value is separated by a comma and space.
Once we have collected user input into variables, we use these to create a query to execute.
If everything is executed fine, the data will be entered into the database and a success message will be displayed. As you can see, the data has been added successfully.
Related Articles
How to Insert Select Option Value in Database Using PHP & MySQL
In this tutorial, You will learn to insert select option values in the database using PHP & MySQL with some simple steps. These steps are very easy to understand and implement in web applications.
Here, I have taken only a single dropdown input field to store select option values in the database. Once you learn it, you will easily customize it according to your project requirement.
How to Store Dropdown Value in Database in PHP
Before getting started it’s coding, you should create the following folder structure –
codingstatus/ |__database.php |__ select-option.php |__ insert-option.php
Learn Also –
Now, let’s start to store dropdown values in the database step by step –
1. Create SQL Database & Table
First of all, You will have to create a database with the name of “codingstatus”.
Database Name – codingstatus
CREATE DATABASE codingstatus;
After that, create a table with the name of “courses” in the database “codingstatus.
CREATE TABLE `courses` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `courseName` varchar(255) DEFAULT NULL, );
2. Connect PHP to MySQL
To insert select option value in the database, you must connect PHP to MySQL database with the help of the following query.
- $hostName – It must contain hostname.
- $userName – It must contain username of the database.
- $password – It must contain password of the database
- $database – It must contain database name.
connect_error) < die("Connection failed: " . $conn->connect_error); > ?>
3. Create Input Field for Select Option
Here, I have created a single dropdown input field with some select options that contain some course name.
File Name – select-option.php
4. Insert Select Option in Database
To insert select option in the database, you will have to implement the following steps to write its code –
Step-1: First of all, apply if condition withisset($_POST[‘submit’]) to check form is set or not
Step-2: Assign course name input to the variable $courseName
Step-3: check course name is empty or not using empty() with if statement. if it is true then follow the next step
Step-4: write MySQL insert query to insert the select option value in the “courses” table
Step-5: if select option is inserted into database successfully then print a success message
File Name – insert-option.php
Insert Select Option Value with another Input Value using PHP & MySQL
Now, You will learn to insert a section option value with another input field like fullName into another table. In the previous step, we have inserted static option values. But In this step, We will display select option values from a database and then insert them into another table of the same database
Before getting started, You will have to create the following two files –
Also, Create another table Name – students with the help of the following query –
CREATE TABLE `students` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `fullName` varchar(255) DEFAULT NULL, `courseName` varchar(255) DEFAULT NULL, );
Create a form and display select option values
First of all, Include database.php and insert-script.php file
Then create an HTML form with a select option & text input field and display data from the database in the select option
Insert Select Option value & Text Input Value
In this step, Write a MySQL query to insert select option value and text input value into the dabase.
File Name – insert-script.php