0% found this document useful (0 votes)
4 views17 pages

WPL 3

Uploaded by

ythombare1972
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

WPL 3

Uploaded by

ythombare1972
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Experiment No.

- 3

Date of Performance: 28-01-25

Date of Submission: 04-02-25

Program Execution/ Timely Viva Experiment Sign with Date


formation/ Submissi (03) Total (10)
correction/ on (01)
ethical practices
(06)

Experiment No. - 3
PHP scripts to connect to the database

3.1 Aim :

To develop PHP scripts that establish a connection with a MySQL database using server-side
scripting, enabling interaction with the database for data retrieval, insertion, updating, and
deletion.

3.2 Course Outcome :

Establish and manage a connection between PHP scripts and a MySQL database, enabling them
to perform essential database operations such as data retrieval, insertion, updating and deletion to
support dynamic and data-driven web applications.

3.3 Learning Objective :


● To understand the fundamentals of database connectivity in web development using PHP
and MySQL.
● To handle connection errors and implement proper error reporting and debugging
techniques.
● To develop secure and efficient PHP scripts for interacting with a database in real-world
web applications.
3.4 Related Theory :

In modern web development, most applications rely on databases to store, retrieve, and manage
data dynamically. PHP, being a powerful server-side scripting language, provides built-in
functions to connect and interact with MySQL databases.
PHP and MySQL together form a popular technology stack known as LAMP (Linux, Apache,
MySQL, PHP).

Using PHP scripts, developers can connect to a database and perform various operations like:
● Data Retrieval (SELECT)

● Data Insertion (INSERT)

● Data Update (UPDATE)

● Data Deletion (DELETE)

Connecting PHP to MySQL


There are two primary methods for connecting to a MySQL database in PHP :

1. MySQLi (MySQL Improved)


● Object-oriented or procedural style.
● Faster and supports prepared statements.

2. PDO (PHP Data Objects)


● More flexible and supports multiple database systems.
● Offers better security and code reusability.

Basic PHP Script to Connect to MySQL Using MySQLi

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "students";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>

CRUD Operations in PHP with MySQL


1. Insert Data into Database

$sql = "INSERT INTO students (name, email) VALUES ('John', '[email protected]')";


if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully.";
} else {
echo "Error: " . mysqli_error($conn);
}

2. Retrieve Data from Database

$sql = "SELECT * FROM students";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
}
} else {
echo "No records found.";
}

3. Update Data

$sql = "UPDATE students SET name='Jane' WHERE id=1";


if (mysqli_query($conn, $sql)) {
echo "Record updated successfully.";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

4. Delete Data

$sql = "DELETE FROM students WHERE id=1";


if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully.";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}

Key PHP Functions Used

Function Description

mysqli_connect() Opens a new connection to the MySQL server

mysqli_query() Executes a SQL query

mysqli_fetch_assoc() Fetches a result row as an associative array

mysqli_num_rows() Returns number of rows in a result set

mysqli_error() Returns the last error description

Security Practices

1. Use Prepared Statements :


Prevent SQL Injection by using mysqli or PDO with parameterized queries.

2. Validate & Sanitize User Input :


Always check and clean user data using filter_var() and htmlspecialchars().

3. Hash Passwords :
Use password_hash() and password_verify() to securely store and check passwords.
4. Handle Errors Safely :
Avoid showing raw SQL errors to users. Use error_log() for internal debugging.

5. Secure Database Credentials :


Store DB login info in a separate config.php file with restricted access.

6. Use HTTPS :
Encrypt all data transmissions between server and browser using SSL.

7. Limit DB User Privileges :


Create specific users for different roles with only necessary permissions.

8. Manage Sessions Securely :


Use session IDs properly, set timeouts, and destroy sessions after logout.

Real-World Applications

● User login and registration systems

● Content Management Systems (CMS)

● E-commerce platforms

● Inventory and employee management systems

3.5 PHP Code Implementation:


Sql connect:

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Create DB:

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>
Create table:

<?php
$servername = "localhost";
$username = "root";
$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 to create table


$sql = "CREATE TABLE employee(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {


echo "Table employee created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Insert Data:

<?php
$servername = "localhost";
$username = "root";
$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 employee(firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
Delete:

<?php
$servername = "localhost";
$username = "root";
$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 to delete a record


$sql = "DELETE FROM employee WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>
Create MySQL Database & Table
CREATE DATABASE CollegeDB;

USE CollegeDB;

CREATE TABLE students (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

email VARCHAR(100) UNIQUE NOT NULL,

mobile VARCHAR(15) NOT NULL,

website VARCHAR(255),

gender ENUM('Male', 'Female', 'Other') NOT NULL,

dob DATE NOT NULL,

address TEXT NOT NULL,

course VARCHAR(100) NOT NULL,

year_of_study INT NOT NULL,

terms_accepted BOOLEAN NOT NULL DEFAULT 0

);

Complete PHP Code

Save this file as register.php and run it on your server (XAMPP, WAMP, etc.).

<?php
// Database Connection
$servername = "localhost"; // Change if needed
$username = "root"; // Your MySQL username
$password = ""; // Your MySQL password
$dbname = "CollegeDB"; // Your database name
$conn = new mysqli($servername, $username, $password, $dbname);

// Check Connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Define Variables & Initialize as Empty


$name = $email = $mobile = $website = $gender = $dob = $address = $course = $year = "";
$terms = 0;
$nameErr = $emailErr = $mobileErr = $websiteErr = $genderErr = $dobErr = $addressErr =
$courseErr = $yearErr = $termsErr = "";

// Form Submission Handling


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Name Validation
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = clean_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}

// Email Validation
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = clean_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

// Mobile Validation
if (empty($_POST["mobile"])) {
$mobileErr = "Mobile number is required";
} else {
$mobile = clean_input($_POST["mobile"]);
if (!preg_match("/^[0-9]{10}$/", $mobile)) {
$mobileErr = "Invalid mobile number (10 digits required)";
}
}

// Website Validation (Optional)


if (!empty($_POST["website"])) {
$website = clean_input($_POST["website"]);
if (!filter_var($website, FILTER_VALIDATE_URL)) {
$websiteErr = "Invalid URL format";
}
}

// Gender Validation
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = $_POST["gender"];
}

// Date of Birth Validation


if (empty($_POST["dob"])) {
$dobErr = "Date of Birth is required";
} else {
$dob = $_POST["dob"];
}

// Address Validation
if (empty($_POST["address"])) {
$addressErr = "Address is required";
} else {
$address = clean_input($_POST["address"]);
}

// Course Validation
if (empty($_POST["course"])) {
$courseErr = "Course is required";
} else {
$course = clean_input($_POST["course"]);
}
// Year of Study Validation
if (empty($_POST["year"])) {
$yearErr = "Year of Study is required";
} else {
$year = clean_input($_POST["year"]);
if (!is_numeric($year) || $year < 1 || $year > 10) {
$yearErr = "Enter a valid study year (1-10)";
}
}

// Terms & Conditions Validation


if (!isset($_POST["terms"])) {
$termsErr = "You must agree to the Terms of Service";
} else {
$terms = 1;
}

// If No Errors, Insert into Database


if (empty($nameErr) && empty($emailErr) && empty($mobileErr) && empty($websiteErr)
&& empty($genderErr) && empty($dobErr) && empty($addressErr) && empty($courseErr)
&& empty($yearErr) && empty($termsErr)) {
$stmt = $conn->prepare("INSERT INTO students (name, email, mobile, website, gender,
dob, address, course, year_of_study, terms_accepted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssii", $name, $email, $mobile, $website, $gender, $dob,
$address, $course, $year, $terms);

if ($stmt->execute()) {
echo "<script>alert('Registration Successful!');</script>";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
}
}

// Function to Clean User Input


function clean_input($data) {
return htmlspecialchars(stripslashes(trim($data)));
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
<title>College Registration Form</title>
</head>
<body>

<h2>College Registration Form</h2>


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>"> <span style="color:
red;">* <?php echo $nameErr; ?></span><br><br>
E-mail: <input type="text" name="email" value="<?php echo $email; ?>"> <span
style="color: red;">* <?php echo $emailErr; ?></span><br><br>
Mobile No: <input type="text" name="mobile" value="<?php echo $mobile; ?>"> <span
style="color: red;">* <?php echo $mobileErr; ?></span><br><br>
Website: <input type="text" name="website" value="<?php echo $website; ?>"> <span
style="color: red;">* <?php echo $websiteErr; ?></span><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="Other"> Other
<span style="color: red;">* <?php echo $genderErr; ?></span><br><br>
DOB: <input type="date" name="dob" value="<?php echo $dob; ?>"> <span style="color:
red;">* <?php echo $dobErr; ?></span><br><br>
Address: <textarea name="address"><?php echo $address; ?></textarea> <span style="color:
red;">* <?php echo $addressErr; ?></span><br><br>
Course: <input type="text" name="course" value="<?php echo $course; ?>"> <span
style="color: red;">* <?php echo $courseErr; ?></span><br><br>
Year: <input type="text" name="year" value="<?php echo $year; ?>"> <span style="color:
red;">* <?php echo $yearErr; ?></span><br><br>
Agree to Terms: <input type="checkbox" name="terms"> <span style="color: red;">* <?php
echo $termsErr; ?></span><br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>
3.6 Execution Steps:
1. Install a local server like XAMPP or WAMP.
2. Create a PHP file (file.php) and paste the above code.
3. Place the file inside the htdocs folder (for XAMPP) or the www folder (for WAMP). 4. Start
the Apache server from the XAMPP/WAMP control panel.
5. Open a web browser and visit http://localhost/file.php.
6. Enter two numbers in the input fields and click "Calculate" to see the results.

3.7 Output:

3.8 Conclusion:
In conclusion, PHP scripts can connect to a database using MySQLi or PDO, enabling efficient
data management and interaction between web applications and databases. Proper error handling
ensures secure and reliable connectivity.

You might also like