0% found this document useful (0 votes)
10 views12 pages

Database Management Using PHP

Uploaded by

shershathbanu.y
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views12 pages

Database Management Using PHP

Uploaded by

shershathbanu.y
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

How to Insert Form Data into Database using PHP ?


In this example , we are going to store data in database which is submitted through
HTML form.
Requirements:
 XAMPP Server (Web Server)
 HTML
 PHP
 MySQL

HTML form: First we create an HTML form that need to take user input from
keyboard.
HTML form is a document which stores information of a user on a web server using
interactive controls.
An HTML form contains different kind of information such as username, password,
contact number, email id etc.
The elements that are used in an HTML form are check box, input box, radio buttons,
submit buttons etc.
With the help of these elements, the information of an user is submitted on the web
server.
The form tag is used to create an HTML form.

Syntax:
<form> Form Elements... </form>
or
To pass the values to next page, we use the page name with the following syntax. We
can use either GET or POST method to sent data to server.
<form action=other_page.php method= POST/GET>
Form Elements...
</form>

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.

Example
<?php
$host = 'localhost';
$user = 'root';
$password = “”';
$dbname = 'origincorp';

$mysqli = new mysqli($host, $user, $password, $dbname);

if(isset($_POST['submit']))
{
$email = $_POST['email'];
$query = "SELECT email FROM emailtbl WHERE email = '$email'";
$result = $mysqli->query($query);
if ($result->num_rows > 0)
{
echo 'Email already exists in the mailing list.';
}
Else
{
$query = "INSERT INTO emailtbl (email) VALUES ('$email')";
if ($mysqli->query($query) === TRUE)
{
echo 'Email added to the mailing list.';
}
Else
{
echo 'Error adding email to the mailing list: ' . $mysqli->error;
}
}
}
$query = "SELECT email FROM emailtbl";
$result = $mysqli->query($query);
if ($result->num_rows > 0)
{
echo '<h2>Mailing List:</h2>';
while($row = $result->fetch_assoc())
{
echo $row['email'] . '<br>';
}
}
else
{
echo 'The mailing list is empty.';
}
$mysqli->close();
?>
<form method="post">
<label for="email">Email Address:</label>
<input type="email" name="email" required>
<button type="submit" name="submit">Submit</button>
</form

Explanation of the above program


1. In PHP, $mysqli = new mysqli($host, $user, $password, $dbname); is a line
of code used to create a new instance of the mysqli class, which is a part of
PHP's MySQLi (MySQL Improved) extension. This line establishes a
connection to a MySQL database.

2. In PHP, isset($_POST['submit']) is a function used to check if a particular


element named 'submit' has been sent to the server via a POST request from an
HTML form.

$_POST: This is a superglobal array in PHP that holds values sent to the server via the
HTTP POST method. When a form is submitted using the POST method, the form
data is stored in this array.

['submit']: This is an array key, referring to a specific input element named 'submit' in
the HTML form. The name attribute of an HTML form element corresponds to keys
in the $_POST array.

isset(): This is a PHP function that checks if a variable is set and is not null. It returns
true if the variable is set and false otherwise.

So, isset($_POST['submit']) checks whether the 'submit' button or input field in the
HTML form has been clicked or submitted. If it has been submitted, this expression
will evaluate to true; otherwise, it will evaluate to false. This check is commonly used
in PHP scripts that process form submissions to determine if the form has been
submitted before processing the form data.

3. $email = $_POST['email'];

This line is used to retrieve data submitted through an HTML form using the
POST method from the input type by name = email.

4. ‘$query = "SELECT email FROM emailtbl WHERE email = '$email'’;

This query is used to retrieve data from a database table named emailtbl.
5. $result = $mysqli->query($query);

This line executes a SQL query against a MySQL database using the mysqli
extension.

$result: This is a variable that will hold the result of the query execution.

After the query is executed, this variable will contain an object representing
the result set returned by the database, or it may contain FALSE if the query
encountered an error.

$mysqli->query($query): is a method call on the $mysqli object, which


represents the connection to the MySQL database.

The query() method is used to execute SQL queries.

It takes a single argument, which is the SQL query string you want to execute
(in this case, the query stored in the $query variable).

So, $result = $mysqli->query($query);

executes the SQL query stored in the $query variable against the MySQL
database connected by the $mysqli object. The result of the query execution is
then stored in the $result variable for further processing.

It's important to note that $result may contain different types of data depending
on the type of query executed.

For example, if the query is a SELECT statement, $result will contain a result
set that can be iterated over to fetch rows of data.

If the query is an INSERT, UPDATE, or DELETE statement, $result may


contain a boolean value indicating whether the operation was successful or an
error occurred.

6. $row = $result->fetch_assoc()

This part fetches the next row of the result set returned by the mysqli query
execution.
The fetch_assoc() method is used to fetch a single row of data as an associative
array, where the keys of the array correspond to the column names in the result
set.

Each iteration of the loop fetches the next row of data from the result set and
stores it in the $row variable.

7. Then using the echo statement the values of the fetched data is displayed on the
screen.

Other examples

PHP code to create database & table in MySQL and insert,

delete, select the data from database.

PROGRAM

<?php

// Connect to MySQL server

$mysqli = new mysqli('localhost', 'root', '', 'employeedb');

$mysqli->query('CREATE TABLE IF NOT EXISTS emptbl( eid INT(6) UNSIGNED


AUTO_INCREMENT PRIMARY KEY,

ename VARCHAR(30) NOT NULL,

email VARCHAR(50) NOT NULL,

ephno VARCHAR(10) NOT NULL,

edept VARCHAR(20) NOT NULL,

esal INT(15) NOT NULL)');

$mysqli->query("INSERT INTO emptbl(ename, email, ephno, edept,esal)

VALUES

('aysha','aysha@gmail.com',9884713895,'HR',200000),
('izyan','izyan@gmail.com',9887613678,'Finance',300000),

('shazana','shazana@gmail.com',8879657885,'Advertising',250000),

('yasmeen','yasmeen@gmail.com',8879657885,'Advertising',150000)");

$mysqli->query("DELETE FROM emptbl WHERE ename ='yasmeen'");

// Select data from the table

$result = $mysqli->query('SELECT * FROM emptbl');

if ($result->num_rows > 0) {

while ($row = $result->fetch_assoc()) {

echo 'EID: ' . $row['eid'] . '<br>';

echo 'EName: ' . $row['ename'] . '<br>';

echo 'Email: ' . $row['email'] . '<br>';

echo 'EPhno: ' . $row['ephno'] . '<br>';

echo 'EDept: ' . $row['edept'] . '<br>';

echo 'ESal: ' . $row['esal'] . '<br>';

echo '<br>';

else

echo 'No data found';

$mysqli->close();
Output

Example

PHP application for student registration form.

PROGRAM

<?php

// initialize variables

$name = $email = $password = '';

// handle form submission


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

// retrieve form data

$name = trim($_POST['name']);

$email = trim($_POST['email']);

$password = trim($_POST['password']);

// validate form data

if (empty($name) || empty($email) || empty($password))

echo 'All fields are required';

elseif (!filter_var($email, FILTER_VALIDATE_EMAIL))

echo 'Invalid email format';

elseif (strlen($password) < 8)

echo 'Password must be at least 8 characters long';

else

// register the user

$mysqli = new mysqli('localhost', 'root', '', 'studentdb');

$mysqli->query("INSERT INTO registrationtbl (name, email, password)

VALUES ('$name', '$email', '$password')");


$mysqli->close();

echo 'Registration successful';

?>

<h2>Student Registration Form</h2>

<form method="post">

<label for="name">Name:</label>

<input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>"


required>

<br><br>

<label for="email">Email Address:</label>

<input type="email" name="email" value="<?php echo

htmlspecialchars($email); ?>" required>

<br><br>

<label for="password">Password:</label>

<input type="password" name="password" required>

<br><br>

<input type="submit" value="Register">

</form>
Explanation

1. $name = trim($_POST['name']);

is a line of code used to retrieve data submitted through an HTML form using
the POST method and remove any leading or trailing whitespace characters
from the input.

trim(): This is a PHP function used to remove whitespace (spaces, tabs, or


newlines) from the beginning and end of a string.

2. elseif (!filter_var($email, FILTER_VALIDATE_EMAIL))


is a conditional statement used to check if a given email address stored in the
variable $email is valid according to the email address format rules.

!filter_var($email, FILTER_VALIDATE_EMAIL):

This is the condition being evaluated. It consists of:

filter_var(): This is a PHP function used to filter a variable using a specified


filter.

In this case, it is used to validate the format of the email address stored in the
variable $email.

$email: This is the variable containing the email address to be validated.

FILTER_VALIDATE_EMAIL: This is a predefined filter constant used with


filter_var() to validate email addresses.

!: This is the logical NOT operator in PHP. It negates the result of the
condition.

So, !filter_var($email, FILTER_VALIDATE_EMAIL) evaluates to true if the


email address stored in $email is not valid according to the specified format.

3. <input type="text" name="name" value="<?php echo

htmlspecialchars($name); ?>" required>

<input type="text">: This part creates an input field where users can input text.
It's one of the types of input fields available in HTML forms.

name="name": This attribute specifies the name of the input field. When the
form is submitted, the value entered into this field will be sent to the server
with the name "name". This name is crucial for identifying the input data on
the server-side.

value="<?php echo htmlspecialchars($name); ?>":

This part sets the initial value of the input field.

It uses PHP to echo out the value stored in the $name variable.

Additionally, the htmlspecialchars() function is used to escape special


characters in the value.
required: This attribute indicates that the input field is required and must be
filled out by the user before the form can be submitted.

If this attribute is present, the browser will not allow the form to be submitted
unless the input field has a value.

You might also like