PHP and SQL database
PHP (Hypertext Preprocessor) is a widely used server-side scripting language for web development. It is
commonly used to interact with SQL databases such as MySQL to store, retrieve, and manipulate data
dynamically.
PHP and LDAP
LDAP is a protocol used to access and maintain directory information services. It is often used for
authentication and user management in enterprise applications.
Connecting PHP with LDAP
To use LDAP in PHP, the ldap extension must be enabled.
Basic PHP LDAP Connection Example:
<?php
$ldap_server = "ldap://example.com";
$ldap_conn = ldap_connect($ldap_server) or die("Could not connect to LDAP server.");
if ($ldap_conn) {
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
$bind = ldap_bind($ldap_conn, "cn=admin,dc=example,dc=com", "password");
if ($bind) {
echo "LDAP bind successful.";
} else {
echo "LDAP bind failed.";
?>
PHP Connectivity with MySQL
PHP connectivity refers to how PHP interacts with databases like MySQL to store, retrieve, and
manipulate data dynamically. This is essential for building web applications such as login systems, online
shopping carts, content management systems, etc.
PHP provides two main ways to connect with MySQL:
1. MySQLi (MySQL Improved) – Supports both procedural and object-oriented approaches.
2. PDO (PHP Data Objects) – Supports multiple databases (MySQL, PostgreSQL, SQLite, etc.).
Steps for Connecting PHP with MySQL using MySQLi
1. Create a MySQL Database and Table.
2. Connect PHP to MySQL Database.
3. Perform CRUD operations (Create, Read, Update, Delete).
4. Close the Database Connection.
1. Create a MySQL Database and Table
Before connecting PHP to MySQL, create a database and a table.
Create Database (Run in MySQL Terminal or phpMyAdmin)
CREATE DATABASE my_database;
Create Table
USE my_database;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
2. Connecting PHP to MySQL Database
We use the mysqli_connect() function to connect PHP with MySQL.
PHP Code for Database Connection (Procedural Approach)
<?php
$servername = "localhost"; // Server name (default: localhost)
$username = "root"; // Database username (default: root)
$password = ""; // Database password (default: empty for local)
$dbname = "my_database"; // Database name
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
echo "Connected successfully";
?>
mysqli_connect($servername, $username, $password, $dbname); establishes the connection.
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } checks if the connection is
successful.
3. Closing the Database Connection
Always close the connection after executing queries to free up resources.
<?php
mysqli_close($conn);
?>
Sending and Receiving Emails
PHP provides built-in functions and external libraries to send and receive emails. The mail() function is
the simplest way to send emails, while external libraries like PHPMailer offer more advanced features
such as attachments, SMTP authentication, and HTML formatting.
1. Sending Emails Using PHP mail() Function
PHP has a built-in mail() function to send emails. However, this function only works if the server is
properly configured to send emails (like with Sendmail on Linux servers). Many shared hosting services
allow this, but it won’t work in local environments like XAMPP unless configured.
Basic Example of Sending an Email
<?php
$to = "[email protected]"; // Receiver's email address
$subject = "Test Email from PHP"; // Email subject
$message = "Hello, this is a test email sent from PHP!"; // Email body
$headers = "From: [email protected]"; // Sender's email address
// Send Email
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email.";
?>
2. Receiving Emails in PHP
PHP cannot directly receive emails, but it can fetch emails from an email server using IMAP or POP3.
Fetching Emails Using IMAP (Example with Gmail)
Use PHP's IMAP extension to fetch emails from a mailbox.
<?php
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX'; // IMAP server
$password = 'your-email-password'; // Your email password
// Connect to mailbox
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect: ' . imap_last_error());
// Fetch emails
$emails = imap_search($inbox, 'ALL');
if ($emails) {
rsort($emails); // Sort emails newest to oldest
foreach ($emails as $email_number) {
$header = imap_headerinfo($inbox, $email_number);
$subject = $header->subject;
$from = $header->fromaddress;
$body = imap_body($inbox, $email_number);
echo "From: $from <br>";
echo "Subject: $subject <br>";
echo "Message: $body <br><br>";
} else {
echo "No emails found.";
// Close connection
imap_close($inbox);
?>
Manipulating data in MySQL using PHP
Manipulating data means performing CRUD operations in MySQL using PHP. CRUD stands for:
C - Create (Insert data)
R - Read (Retrieve data)
U - Update (Modify existing data)
D - Delete (Remove data)
After successfully connecting, we can perform Create, Read, Update, and Delete operations.
(A) Insert Data into MySQL
Inserting data means adding new records into a MySQL database table using PHP.
<?php
$sql = "INSERT INTO users (name, email, password) VALUES ('John Doe', '[email protected]', '12345')";
if (mysqli_query($conn, $sql)) {
echo "New record inserted successfully";
} else {
echo "Error: " . mysqli_error($conn);
?>
INSERT INTO users (name, email, password) VALUES (...) adds new data to the table.
mysqli_query($conn, $sql); executes the query.
(B) Retrieve Data from MySQL
Retrieving data from MySQL means fetching stored records from a database table using SQL's SELECT
statement and displaying them using PHP.
<?php
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
} else {
echo "No records found";
?>
SELECT id, name, email FROM users; fetches all user records.
mysqli_fetch_assoc($result); fetches rows one by one.
(C) Update Data in MySQL
The UPDATE statement in MySQL is used to modify existing records in a table. You can update one or
multiple columns based on a specific condition using the WHERE clause.
<?php
$sql = "UPDATE users SET email='[email protected]' WHERE name='John Doe'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
?>
UPDATE users SET email='[email protected]' WHERE name='John Doe'; modifies existing
data.
(D) Delete Data from MySQL
The DELETE statement in MySQL is used to remove specific records from a table. It is commonly used
when data is no longer needed or needs to be replaced with updated information.
<?php
$sql = "DELETE FROM users WHERE name='John Doe'";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
?>
DELETE FROM users WHERE name='John Doe'; removes a record from the table.