WPL 3
WPL 3
- 3
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.
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.
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)
<?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!";
?>
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
4. Delete Data
Function Description
Security Practices
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.
6. Use HTTPS :
Encrypt all data transmissions between server and browser using SSL.
Real-World Applications
● E-commerce platforms
<?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);
}
$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);
}
$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);
}
$conn->close();
?>
Create MySQL Database & Table
CREATE DATABASE CollegeDB;
USE CollegeDB;
website VARCHAR(255),
);
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);
}
// 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)";
}
}
// Gender Validation
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = $_POST["gender"];
}
// 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)";
}
}
if ($stmt->execute()) {
echo "<script>alert('Registration Successful!');</script>";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
}
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>College Registration Form</title>
</head>
<body>
</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.