PHP CRUD operations

Question

Answers ( 1 )

    0
    2024-01-11T18:05:25+00:00

    CRUD stands for Create, Read, Update, and Delete, which are the four basic functions of persistent storage in many applications, especially web applications.

    Here's a brief overview and example for each operation in PHP:

    1. Create (Insert)

    To insert data into a database, you use the INSERT INTO statement.

    Example:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "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 MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";
    
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    $conn->close();
    ?>
    

    2. Read (Select)

    To read or select data from a database, use the SELECT statement.

    Example:

    <?php
    $sql = "SELECT id, firstname, lastname FROM MyGuests";
    $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"]. "<br>";
        }
    } else {
        echo "0 results";
    }
    ?>
    

    3. Update

    To update existing records in a database, use the UPDATE statement.

    Example:

    <?php
    $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
    
    if ($conn->query($sql) === TRUE) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: " . $conn->error;
    }
    ?>
    

    4. Delete

    To delete records from a database, use the DELETE FROM statement.

    Example:

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

    Notes

    • Always ensure that your PHP code is securely handling data to prevent SQL injection attacks.
    • These examples assume you have a MySQL database and are using the MySQLi extension.
    • Replace $servername, $username, $password, and $dbname with your actual database details.

Leave an answer