Skip to content
PHP Logo

What are the basic CRUD operations in PHP and how are they typically implemented?

CRUD operations refer to Create, Read, Update, and Delete operations on a database. In PHP, these operations are typically implemented using SQL queries to interact with the database. Here is an example of how to implement basic CRUD operations in PHP: Create (INSERT):

php
// Connect to database
$conn = new mysqli('localhost', 'username', 'password', 'database');

// Insert data into table
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
$conn->query($sql);
```

Read (SELECT):
```php
// Connect to database
$conn = new mysqli('localhost', 'username', 'password', 'database');

// Select data from table
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Fetch and display data
while($row = $result->fetch_assoc()) {
    echo $row['column1'] . ' ' . $row['column2'] . '<br>';
}
```

Update (UPDATE):
```php
// Connect to database
$conn = new mysqli('localhost', 'username', 'password', 'database');

// Update data in table
$sql = "UPDATE table_name SET column1='new_value' WHERE id=1";
$conn->query($sql);
```

Delete (DELETE):
```php
// Connect to database
$conn = new mysqli('localhost', 'username', 'password', 'database');

// Delete data from table
$sql = "DELETE FROM table_name WHERE id=1";
$conn->query($sql);