Superglobals in PHP

MySQL and Databases in PHP

Learn how to interact with MySQL databases using PHP. This guide covers connecting to MySQL, creating databases and tables, and performing various operations like inserting, retrieving, updating, and deleting data.

What is an RDBMS?

An RDBMS (Relational Database Management System) is a type of database management system that stores data in a structured format, using rows and columns. Each table in an RDBMS represents a specific entity, and the relationships between these tables are maintained through keys.

Using MySQL with PHP

  1. Connecting to MySQL with PHP
  2. To interact with a MySQL database using PHP, you first need to establish a connection. You can use either the mysqli or PDO extension. Here’s how to do it with both:

    Using mysqli:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "mydatabase";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
    ?>

    Using PDO:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "mydatabase";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
        // Set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
    } catch (PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
    ?>
  3. Creating a Database and Table
  4. To create a database and table, you can use SQL commands. Here’s an example of how to do this with PHP:

    Creating a Database:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password);
    
    // Create database
    $sql = "CREATE DATABASE mydatabase";
    if ($conn->query($sql) === TRUE) {
        echo "Database created successfully";
    } else {
        echo "Error creating database: " . $conn->error;
    }
    
    // Close connection
    $conn->close();
    ?>

    Creating a Table:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "mydatabase";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    
    // SQL to create table
    $sql = "CREATE TABLE Users (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        firstname VARCHAR(30) NOT NULL,
        lastname VARCHAR(30) NOT NULL,
        email VARCHAR(50),
        reg_date TIMESTAMP
    )";
    
    if ($conn->query($sql) === TRUE) {
        echo "Table Users created successfully";
    } else {
        echo "Error creating table: " . $conn->error;
    }
    
    // Close connection
    $conn->close();
    ?>
  5. Inserting Data into a Table
  6. To insert data into a table, use the INSERT INTO SQL statement:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "mydatabase";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    
    // SQL to insert data
    $sql = "INSERT INTO Users (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;
    }
    
    // Close connection
    $conn->close();
    ?>
  7. Retrieving Data from a Table
  8. To retrieve data, use the SELECT SQL statement.

    Using mysqli:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "mydatabase";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    
    // SQL to select data
    $sql = "SELECT id, firstname, lastname, email FROM Users";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        // Output data of each row
        while($row = $result->fetch_assoc()) {
            echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. " - Email: " . $row["email"]. "<br>";
        }
    } else {
        echo "0 results";
    }
    
    // Close connection
    $conn->close();
    ?>
  9. Updating and Deleting Data
  10. You can update and delete records using the UPDATE and DELETE SQL statements:

    Updating Data:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "mydatabase";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    
    // SQL to update data
    $sql = "UPDATE Users SET lastname='Smith' WHERE id=1";
    
    if ($conn->query($sql) === TRUE) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: " . $conn->error;
    }
    
    // Close connection
    $conn->close();
    ?>

    Deleting Data:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "mydatabase";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    
    // SQL to delete data
    $sql = "DELETE FROM Users WHERE id=1";
    
    if ($conn->query($sql) === TRUE) {
        echo "Record deleted successfully";
    } else {
        echo "Error deleting record: " . $conn->error;
    }
    
    // Close connection
    $conn->close();
    ?>
Previous Next
Modern Footer