Skip to content
PHP Logo

How can PHP developers efficiently display, insert, update, and delete data using Ajax and Mysqli?

To efficiently display, insert, update, and delete data using Ajax and Mysqli, PHP developers can create separate PHP files for each operation (display, insert, update, delete), and then use Ajax to send requests to these PHP files asynchronously. The PHP files will interact with the database using Mysqli queries to perform the desired operation.

php
// display.php
<?php
// Connect to database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Select data from database
$query = "SELECT * FROM table_name";
$result = $connection->query($query);

// Output data in JSON format
$data = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($data);

// Close database connection
$connection->close();
?>
```

```php
// insert.php
<?php
// Connect to database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Get data from Ajax request
$data = json_decode(file_get_contents('php://input'), true);

// Insert data into database
$query = "INSERT INTO table_name (column1, column2) VALUES ('".$data['value1']."', '".$data['value2']."')";
$connection->query($query);

// Close database connection
$connection->close();
?>
```

```php
// update.php
<?php
// Connect to database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Get data from Ajax request
$data = json_decode(file_get_contents('php://input'), true);

// Update data in database
$query = "UPDATE table_name SET column1 = '".$data['value1']."', column2 = '".$data['value2']."' WHERE id = ".$data['id'];
$connection->query($query);

// Close database connection
$connection->close();
?>
```

```php
// delete.php
<?php
// Connect to database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Get data from Ajax request
$data = json_decode(file_get_contents('php://input'), true);

// Delete data from database
$query = "DELETE FROM table_name WHERE id = ".$data['id'];
$connection->query($query);

// Close database connection
$connection->close();
?>