In this post, I will walk you through the process of creating a user table using MySQLi prepared statements in PHP 8. Additionally, it will demonstrate how to enable inline editing of the table rows, allowing users to click on a row to edit its contents and automatically save the changes to the database.
Step 1: Set Up Your Database
First, ensure you have a MySQL database set up with a users table. Here’s a simple SQL statement to create the table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
Step 2: Connect to the Database
Create a PHP file (e.g., db.php) to handle the database connection using MySQLi.
<?php
$host = 'localhost';
$user = 'your_username';
$password = 'your_password';
$database = 'your_database';
$mysqli = new mysqli($host, $user, $password, $database);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
?>
Step 3: Fetch Users from the Database
In your main PHP file (e.g., index.php), include the database connection and fetch the users.
<?php
include 'db.php';
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
?>
<table id="userTable">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php while ($row = $result->fetch_assoc()): ?>
<tr data-id="<?= $row['id'] ?>">
<td class="editable" data-field="name"><?= htmlspecialchars($row['name']) ?></td>
<td class="editable" data-field="email"><?= htmlspecialchars($row['email']) ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
Step 4: Enable Inline Editing with JavaScript
Add JavaScript to handle the inline editing functionality. This script will allow users to click on a table cell to edit its content.
<script>
document.querySelectorAll('.editable').forEach(cell => {
cell.addEventListener('click', function() {
const originalContent = this.innerText;
const input = document.createElement('input');
input.value = originalContent;
this.innerHTML = '';
this.appendChild(input);
input.focus();
input.addEventListener('blur', () => {
const newValue = input.value;
const field = this.getAttribute('data-field');
const rowId = this.parentElement.getAttribute('data-id');
// Save the new value to the database
fetch('update.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id: rowId, field: field, value: newValue })
})
.then(response => response.json())
.then(data => {
if (data.success) {
this.innerText = newValue;
} else {
this.innerText = originalContent; // Revert to original if failed
}
});
});
});
});
</script>
Step 5: Create the Update Script
Create an update.php file to handle the AJAX request and update the database.
<?php
include 'db.php';
$data = json_decode(file_get_contents('php://input'), true);
$id = $data['id'];
$field = $data['field'];
$value = $data['value'];
$stmt = $mysqli->prepare("UPDATE users SET $field = ? WHERE id = ?");
$stmt->bind_param('si', $value, $id);
$success = $stmt->execute();
echo json_encode(['success' => $success]);
?>
By following these steps, you have successfully created a user table with inline editing capabilities using PHP 8 and MySQLi prepared statements. This approach not only enhances user experience but also ensures that your application remains secure and efficient.
Happy coding… 🙂
I’ve been designing web applications—on and off—since 2001, back when animated GIFs were all the rage and ‘responsive design’ meant answering your client’s emails. Over the past 14 years, I’ve kept pace with the ever-evolving trends in PHP development, successfully delivering a variety of projects that made my clients happy (and kept me caffeinated).
This website serves as my soapbox—a place to share the insights I’ve picked up along the way with anyone curious enough to dive in. Welcome aboard!
Need some custom work done? Or, just want to reach out? Email: dan@danoriordan.com