"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

PHP and MySQL

 

PHP is commonly used with MySQL to create dynamic, database-driven websites. With MySQL, you can store, retrieve, update, and delete data efficiently.


Connecting to MySQL Server Using WAMP/XAMPP

1.      Make sure WAMP or XAMPP is installed and running. Start:

o    Apache server

o    MySQL server

2.      PHP MySQL connection example using mysqli:

<?php
$servername = "localhost"; // MySQL server
$username = "root";        // default username for WAMP/XAMPP
$password = "";            // default password is empty
$dbname = "my_database";   // database name
 
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
 
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Note: On XAMPP/WAMP, the default username is root and password is usually empty.


CRUD Operations (Create, Read, Update, Delete)

1. Create (Insert Data)

$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $conn->error;
}

2. Read (Select Data)

$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
 
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}

3. Update (Modify Data)

$sql = "UPDATE users SET email='john.doe@example.com' WHERE id=1";
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

4. Delete (Remove Data)

$sql = "DELETE FROM users WHERE id=1";
if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}

Closing the Connection

$conn->close();

Using PHP with MySQL allows you to build fully dynamic websites. By mastering CRUD operations, you can handle almost any type of database functionality, from user registrations to blog posts and e-commerce systems.

 

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)