- PHP Basics
- PHP Home
- PHP Environment Setup
- PHP Getting Started
- PHP Basic Syntax
- PHP echo
- PHP print
- PHP echo Vs print
- PHP Comments
- PHP Data Types
- PHP Variables
- PHP Variable Scope
- PHP gettype()
- PHP Constants
- PHP Operators
- PHP Program Control
- PHP Decision Making
- PHP if-elseif-else
- PHP switch
- PHP Loops
- PHP for Loop
- PHP while Loop
- PHP do-while Loop
- PHP foreach Loop
- PHP break & continue
- PHP Popular Topics
- PHP Arrays
- PHP print_r()
- PHP Strings
- PHP Functions
- PHP References
- PHP Object Oriented
- PHP Object Oriented
- PHP Classes & Objects
- PHP Member Variable
- PHP Member Function
- PHP Encapsulation
- PHP Data Abstraction
- PHP Inheritance
- PHP Constructor Destructor
- PHP Polymorphism
- PHP Web Developments
- PHP Web Developments
- PHP GET & POST
- PHP Read Requested Data
- PHP File Handling (I/O)
- PHP File Handling (I/O)
- PHP fopen() | Open File
- PHP Create a File
- PHP fwrite() | Write to File
- PHP fread() | Read File
- PHP feof()
- PHP fgetc()
- PHP fgets()
- PHP fclose() | Close File
- PHP unlink() | Delete File
- PHP Append to File
- PHP copy() | Copy File
- PHP file_get_contents()
- PHP file_put_contents()
- PHP file_exists()
- PHP filesize()
- PHP rename() | Rename File
- PHP fseek()
- PHP ftell()
- PHP rewind()
- PHP disk_free_space()
- PHP disk_total_space()
- PHP mkdir() | Create Directory
- PHP rmdir() | Remove Directory
- PHP glob() | Get Files/Directories
- PHP basename() | Get filename
- PHP dirname() | Get Path
- PHP filemtime()
- PHP file()
- PHP Advanced
- PHP Cookies
- PHP Sessions
- PHP Send Emails
- PHP Serialization
- PHP Namespaces
- PHP File Upload
- PHP Date and Time
- PHP Image Processing
- PHP Regular Expression
- PHP Predefined Variables
- PHP Error Handling
- PHP Debugging
- PHP and MySQLi Tutorial
- PHP and MySQLi Home
- PHP MySQLi Setup
- PHP MySQLi Create DB
- PHP MySQLi Create Table
- PHP MySQLi Connect to DB
- PHP MySQLi Insert Record
- PHP MySQLi Fetch Record
- PHP MySQLi Update Record
- PHP MySQLi Delete Record
- PHP MySQLi SignUp Page
- PHP MySQLi LogIn Page
- PHP MySQLi Store User Data
- PHP MySQLi Close Connection
- PHP connect_errno
- PHP connect_error
- PHP query()
- PHP fetch_row()
- PHP fetch_assoc()
- PHP fetch_array()
- PHP free_result()
- PHP error
- PHP prepare()
- PHP bind_param()
- PHP execute()
- PHP fetch()
- PHP store_result()
- PHP num_rows
- PHP bind_result()
- PHP get_result()
- PHP mysqli_result Class
- PHP Error Constants
- PHP mysqli_driver()
- PHP Misc
- PHP error_reporting()
- PHP Escape Special Characters
- PHP htmlspecialchars()
- PHP new
- PHP header()
- PHP getallheaders()
- PHP empty()
- PHP isset()
- PHP unset()
- PHP exit()
- PHP exit Vs break
- PHP include()
- PHP require()
- PHP include() Vs require()
- PHP AJAX & XML
- PHP AJAX
- PHP XML
- PHP File Handling Functions
- PHP abs()
- PHP Test
- PHP Online Test
- Give Online Test
- All Test List
PHP MySQLi Code to Store Form Data in Database
This article is created to describe the way, to store form data or the data entered by user on the web, using PHP MySQLi object-oriented and procedural script.
Store Form Data using PHP MySQLi Object-Oriented Script
I really do not know about your requirement, on saving or storing of user (form) data in the database. I mean,
what type of data, you need to store?
But here, I am going to create a form, where user fills their username along with a comment, to store in the
database.
Whatever, the data you need to store, the process will be same, like shown in the example given below:
<?php if($_SERVER["REQUEST_METHOD"] == "POST") { $server = "localhost"; $user = "root"; $pass = ""; $db = "codescracker"; $conn = new mysqli($server, $user, $pass, $db); if($conn -> connect_errno) { echo "Database connection failed!<BR>"; echo "Reason: ", $conn -> connect_error; exit(); } else { $user = $_POST["user"]; $data = $_POST["data"]; $sql = "INSERT INTO comments(user, data) VALUES('$user', '$data');"; $res = $conn -> query($sql); if($res) { echo "Data inserted into the database successfully!"; // block of code, to process further... } else { echo "Something went wrong!<BR>"; echo "Error description: ", $conn -> error; exit(); } } $conn -> close(); } ?> <HTML> <BODY> <FORM METHOD="POST"> Enter Data:<BR> <INPUT TYPE="text" NAME="user" MAXLENGTH="40" PLACEHOLDER="Enter Username"><BR> <TEXTAREA TYPE="text" STYLE="height:60px;" NAME="data" MAXLENGTH="240" PLACEHOLDER="Write Comment"></TEXTAREA><BR> <INPUT TYPE="submit" NAME="comment" VALUE="Submit"> </FORM> </BODY> </HTML>
Before executing the above example of storing form data in database, a database named codescracker, in which, a table named comments must be available, with following fields:
All the data, should be stored in this table. Now here is the sample initial output produced by above PHP MySqLi object-oriented script to store user data/comment in the database:
Now enter the data, say codescracker in Username field, whereas PHP is Fun?
Is not it? in Comment field. And then hit Submit button. Here is the output, you will see:
Here is the snapshot of the table, customer, after executing the above script:
Note - The mysqli() is used to open a connection to the MySQL database server, in object-oriented style.
Note - The new keyword is used to create a new object.
Note - The connect_errno is used to get/return the error code (if any) from last connect call, in object-oriented style.
Note - The connect_error is used to get the error description (if any) from last connection, in object-oriented style.
Note - The query() is used to perform query on the MySQL database, in object-oriented style.
Note - The error is used to return the description of error (if any), by the most recent function call, in object-oriented style.
Note - The exit() is used to terminate the execution of the current PHP script.
Note - The close() is used to close an opened connection, in object-oriented style.
The above example, can also be created in this way:
<?php if($_SERVER["REQUEST_METHOD"] == "POST") { $conn = new mysqli("localhost", "root", "", "codescracker"); if(!$conn -> connect_errno) { $user = $_POST["user"]; $data = $_POST["data"]; $sql = "INSERT INTO comments(user, data) VALUES('$user', '$data');"; if($conn -> query($sql)) echo "Data inserted into the database successfully!"; } $conn -> close(); } ?> <HTML> <BODY> <FORM METHOD="POST"> Enter Data:<BR> <INPUT TYPE="text" NAME="user" MAXLENGTH="40" PLACEHOLDER="Enter Username"><BR> <TEXTAREA TYPE="text" STYLE="height:60px;" NAME="data" MAXLENGTH="240" PLACEHOLDER="Write Comment"></TEXTAREA><BR> <INPUT TYPE="submit" NAME="comment" VALUE="Submit"> </FORM> </BODY> </HTML>
Store Form Data using PHP MySQLi Procedural Script
To store form data using PHP MySQLi procedural script, follow the example given below:
<?php if($_SERVER["REQUEST_METHOD"] == "POST") { $conn = mysqli_connect("localhost", "root", "", "codescracker"); if(mysqli_connect_errno()) { echo "Database connection failed!<BR>"; echo "Reason: ", mysqli_connect_error(); exit(); } else { $user = $_POST["user"]; $data = $_POST["data"]; $sql = "INSERT INTO comments(user, data) VALUES('$user', '$data');"; if(mysqli_query($conn, $sql)) echo "Data inserted into the database successfully!"; else { echo "Something went wrong!<BR>"; echo "Error description: ", $conn -> error; exit(); } } mysqli_close($conn); } ?> <HTML> <BODY> <FORM METHOD="POST"> Enter Data:<BR> <INPUT TYPE="text" NAME="user" MAXLENGTH="40" PLACEHOLDER="Enter Username"><BR> <TEXTAREA TYPE="text" STYLE="height:60px;" NAME="data" MAXLENGTH="240" PLACEHOLDER="Write Comment"></TEXTAREA><BR> <INPUT TYPE="submit" NAME="comment" VALUE="Submit"> </FORM> </BODY> </HTML>
Note - The mysqli_connect() is used to open a connection to the MySQL database server, in procedural style.
Note - The mysqli_connect_errno() is used to get/return the error code (if any) from last connect call, in procedural style.
Note - The mysqli_connect_error() is used to return the error description (if any) from the last connection, in procedural style.
Note - The mysqli_query() is used to perform query on the MySQL database, in procedural style.
Note - The mysqli_error() is used to return the description of error (if any), by the most recent function call, in object-oriented style.
Note - The mysqli_close() is used to close an opened connection to the MySQL database, in procedural style.
The examples given above, looks very simple and basic. Also the data are getting saved in the database, without even basic filter, that may be sometime malicious. Therefore, let me create another safe and secure PHP MySQLi script, that does the same job, of storing form data in database.
PHP MySQLi Safe and Secure Script to Save Form Data in Database
This example of storing user form data in database, is created using PHP MySQLi safe and secure object-oriented script.
<?php $conn = new mysqli("localhost", "root", "", "codescracker"); if($conn->connect_errno) { echo "Database connection failed!<BR>"; echo "Reason: ", $conn->connect_error; exit(); } if($_SERVER["REQUEST_METHOD"] == "POST") { function validate($x) { $x = trim($x); $x = stripslashes($x); $x = htmlspecialchars($x); return $x; } $stmt = $conn->prepare("INSERT INTO comments(user, data) VALUES (?, ?)"); $stmt->bind_param("ss", $user, $data); $user = validate($_POST["user"]); $data = validate($_POST["data"]); if($stmt->execute()) echo "Your comment posted successfully!"; } ?> <HEAD> <STYLE> .myForm{width: 380px; margin: auto; padding: 12px;} .myForm h2{text-align: center;} .myForm input, textarea{width: 100%;} .myForm input{padding: 8px; margin-bottom: 8px;} .myForm textarea{height: 80px; padding: 8px; margin-bottom: 8px;} button{width: 100%; background-color: #008080; color: white; font-size: 1em; padding: 12px;} button:hover{cursor: pointer;} .display{width: 380px; margin: auto; border-left: 2px solid #ccc; padding: 12px;} .commentBox{margin-bottom: 12px;} .right{text-align: right;} </STYLE> <HTML> <BODY> <DIV CLASS="myForm"> <FORM METHOD="POST"> <h2>Enter the Comment</h2> <INPUT TYPE="text" NAME="user" MAXLENGTH="40" PLACEHOLDER="Enter Username"><BR> <TEXTAREA TYPE="text" NAME="data" MAXLENGTH="240" PLACEHOLDER="Write Comment"></TEXTAREA><BR> <BUTTON TYPE="submit">Post</BUTTON> </FORM> </DIV> <DIV CLASS="display"> <h2>Latest Comments</h2> <?php $sql = "SELECT * FROM comments ORDER BY id DESC LIMIT 10"; if($result = $conn->query($sql)) { while($row = $result->fetch_row()) { echo "<div class=\"commentBox\">"; echo "By <B>", $row[2], "</B><BR>"; echo $row[3]; echo "<div class=\"right\">", $row[1], "</div>"; echo "</div>"; } } $conn->close(); ?> </DIV> </BODY> </HTML>
The output produced by above PHP example is:
Now enter your username along with comment, then hit on the Post button, to post your comment on the website. For example, let me type some random anonymous username along with comment:
Now click on the Post button, here is the new output:
Notice your latest comment, that is added on the website.
Note - The prepare() is used to prepare an SQL statement before its execution on the MySQL database, in object-oriented style, to avoid SQL injection.
Note - The bind_param() is used to bind variables to a prepared statement, as parameters, in object-oriented style.
Note - The execute() is used to execute a prepared statement on the MySQL database, in object-oriented style.
« Previous Tutorial Next Tutorial »
Follow/Like Us on Facebook
Subscribe Us on YouTube