Topics Covered in This PHP & MySQL Tutorial:
The UPDATE Statement, Update Form, Display Data in the Update Form, Display Checkboxes, Hidden Fields
Learning Path Overview
SQL Fundamentals
Master UPDATE syntax with prepared statements and parameter binding for secure database operations.
Form Integration
Build dynamic update forms with pre-populated data, checkboxes, and hidden fields for user management.
Security Best Practices
Implement proper WHERE clauses and prepared statements to prevent accidental bulk updates and SQL injection.
Exercise Overview
This comprehensive exercise will demonstrate the SQL syntax for updating database records and guide you through building a professional update form with advanced features including checkboxes and hidden fields. You'll learn essential techniques for user data management that form the backbone of modern web applications, from content management systems to user account portals.
Update Syntax
Updating database records is straightforward, but precision is critical. When updating a user in the users table, the syntax follows this pattern:
UPDATE users
SET
firstName = 'Albert',
lastName = 'Einstein',
email = 'albert@someemail.com'
WHERE
id = 231
This statement updates the users table, setting the firstName, lastName, and email to their corresponding values for the record where id equals 231. The WHERE clause is absolutely essential—without it, you would update every row in the database, potentially causing catastrophic data loss. Always specify which particular row you want to update. This is why implementing a unique id field in every table is not just best practice—it's a fundamental requirement for data integrity and safe operations.
Always include a WHERE clause in UPDATE statements. Without it, you will update every row in the database, potentially causing catastrophic data loss.
UPDATE Statement Structure
Specify Table
Begin with UPDATE followed by the target table name
SET Values
Use SET to define which columns to update with new values
WHERE Condition
Always specify which rows to update using a unique identifier
A Simple Example
Let's implement a basic update operation to see these concepts in action. First, we need to identify a specific record in the users table to modify.
Access phpMyAdmin through your development environment:
Mac- Switch to MAMP PRO.
- Click the WebStart button.
- In the page that opens, click on Tools and choose phpMyAdmin.
- Open a browser and go to http://localhost
- On the start page, in the Tools section click phpMyAdmin.
On the left sidebar, click phpclass_yourname to access your database.
Next to the users table, click the Browse icon
to view all records in the table.Review all records in the database and select one you'd like to modify, noting its id value. For consistency, you can choose the first record with id = 1.
Open update-easy.php from the phpclass folder in your code editor.
Initialize the variables for our update operation. At the top of the page, add this PHP block (replace the $id value with the id you selected):
<?php $firstName = 'Update'; $lastName = 'Me'; $email = 'updated@update.com'; $id = 1; ?>Include the database connection script by adding this line:
$firstName = 'Update'; $lastName = 'Me'; $email = 'updated@update.com'; $id = 1; require_once('inc/dbConnect.php');Now we'll construct the UPDATE statement using prepared statement placeholders for security:
require_once('inc/dbConnect.php'); $SQL = "UPDATE users SET firstName = ?, lastName = ?, email = ? WHERE id = ? ";Notice we're using ? placeholders—this is essential for prepared statements, which protect against SQL injection attacks.
Initialize and prepare the statement object. This follows the standard prepared statement pattern:
$stmt = $conn->stmt_init(); $stmt->prepare($SQL);Bind the parameters to their respective placeholders:
$stmt = $conn->stmt_init(); $stmt->prepare($SQL); $stmt->bind_param('sssi', $firstName, $lastName, $email, $id);Execute the statement and implement proper error handling:
$stmt = $conn->stmt_init(); $stmt->prepare($SQL); $stmt->bind_param('sssi', $firstName, $lastName, $email, $id); $stmt->execute(); if ($stmt->error) { echo $stmt->error; exit(); }Save the file and test it in your browser:
- Mac: localhost:8888/phpclass/update-easy.php
- Windows: localhost/phpclass/update-easy.php
A blank page indicates successful execution—no news is good news in this case.
Return to phpMyAdmin and Browse the users table to verify the changes.
Locate the record with the id you updated—you should see your changes reflected in the database.
Database Setup Process
Access phpMyAdmin
Use MAMP PRO WebStart on Mac or localhost on Windows
Browse Users Table
Navigate to phpclass database and select a record ID to modify
Execute Update
Run the prepared statement with bound parameters and error checking
Update Form
Now we'll move beyond basic updates to build a sophisticated, real-world update form suitable for user administration systems. This approach mirrors what you'd find in professional applications like WordPress admin panels or customer relationship management systems.
Open userList.php from the update folder.
Load the page in your browser:
- Mac: localhost:8888/phpclass/update/userList.php
- Windows: localhost/phpclass/update/userList.php
You'll see a comprehensive list of all records in the users table. The first column contains "Edit" links that route users to an update form. Notice the Subscribe column displays raw 1s and 0s—we'll transform these into user-friendly "Yes" or "No" values.
Return to your code editor.
Around line 49, locate the code that displays the $subscribe variable:
<td><?php echo $subscribe; ?></td>Instead of a traditional if-else statement, we'll use PHP's ternary operator—a powerful shorthand that's perfect for simple conditional displays like this.
Replace the existing code with this ternary operator implementation:
<td><?php echo ($subscribe) ? 'Yes' : 'No' ?></td>The ternary operator uses three components: a test expression in parentheses, followed by a question mark, then two possible return values separated by a colon. The first value is returned if the test is true, the second if false. This creates cleaner, more readable code for simple conditions.
Next, we'll create dynamic links that pass user IDs to our update form. The resulting anchor tag will look like this:
<a href="userform.php?id=3">Edit</a>The question mark initiates the query string, making everything after it available as URL variables through PHP's $_GET superglobal array.
Around line 43, find the static Edit link:
<td><a href="userform.php">Edit</a></td>Add the query string parameter structure:
<td><a href="userform.php?id=">Edit</a></td>Complete the dynamic link by adding the PHP that outputs each user's unique ID:
<td><a href="userform.php?id=<?php echo $id; ?>">Edit</a></td>Save your changes and reload the page:
- Mac: localhost:8888/phpclass/update/userList.php
- Windows: localhost/phpclass/update/userList.php
Click several Edit links and observe how each directs you to userForm.php with the corresponding user ID in the URL—this is the foundation of record-specific editing.
The ternary operator (condition ? true_value : false_value) provides shorthand notation for simple if-else statements, perfect for converting database boolean values to user-friendly text.
Building Dynamic Edit Links
Add URL Parameter
Append ?id= to the userform.php link to pass the user ID
Echo User ID
Use PHP to dynamically insert each user's ID into the URL
Access via $_GET
Retrieve the ID on the target page using PHP's $_GET superglobal array
Display Data in the Update Form
The next step is pre-populating form fields with existing user data—a crucial user experience feature that allows users to see current values before making changes.
Return to your code editor.
Open userForm.php from the update folder.
Examine the code at the top of the page—we've provided the SELECT statement and PHP logic to retrieve the user record. Note line 9 where we capture the URL variable:
$stmt->bind_param('i', $_GET['id']);This binds the user ID from the URL to our prepared statement parameter, demonstrating how data flows from the user list through the URL to the database query.
Let's populate the first name field. Around line 36, you'll see an empty value attribute. Fill it with the user data:
<input name="firstName" type="text" id="firstName" size="40" value="<?php echo $firstName; ?>">Test this change by saving the file and navigating to:
- Mac: localhost:8888/phpclass/update/userList.php
- Windows: localhost/phpclass/update/userList.php
Click any Edit link—the first name field should now display the existing user data.
Return to your code editor to implement the same pattern for the remaining fields.
Around line 40, populate the last name field:
<input name="lastName" type="text" id="lastName" size="40" value="<?php echo $lastName; ?>">Around line 44, populate the email field:
<input name="email" type="text" id="email" size="40" value="<?php echo $email; ?>">For the comments textarea (around line 54
<textarea name="comments" id="comments" cols="38" rows="5"><?php echo $comments; ?></textarea>Important: Keep this on a single line in your code. Whitespace inside textarea elements is preserved and displayed to users, so any extra spaces or line breaks will appear in the form.
Save your changes and test the complete form:
- Mac: localhost:8888/phpclass/update/userList.php
- Windows: localhost/phpclass/update/userList.php
Click any Edit link—all text fields should now display the existing user data, providing a seamless editing experience.
The ternary operator (condition ? true_value : false_value) provides shorthand notation for simple if-else statements, perfect for converting database boolean values to user-friendly text.
Building Dynamic Edit Links
Add URL Parameter
Append ?id= to the userform.php link to pass the user ID
Echo User ID
Use PHP to dynamically insert each user's ID into the URL
Access via $_GET
Retrieve the ID on the target page using PHP's $_GET superglobal array
Display Checkboxes
Handling checkboxes requires a different approach than text fields. We need to conditionally add the checked attribute based on the user's previous selections. This is where conditional logic becomes essential for maintaining form state.
Return to your code editor.
In userForm.php, locate the subscribe checkbox around line 59. Add a conditional statement that checks the subscription status:
<input name="subscribe" type="checkbox" id="subscribe" value="1" <?php if ($subscribe) {echo 'checked';}?>>- Save and test your changes:
- Mac: localhost:8888/phpclass/update/userList.php
- Windows: localhost/phpclass/update/userList.php
Click an Edit link and observe whether the subscribe checkbox reflects the user's current subscription status.
The publications checkboxes require a more sophisticated approach since they're stored as a delimited string. We need to search within that string for specific values. Return to your code editor.
Around line 49, find the Daily Racing Form checkbox and add this conditional framework:
<input name="publications[]" type="checkbox" id="publications_drf" value="Daily Racing Form" <?php if () { echo 'checked';} ?>> Daily Racing Form</label>Complete the condition using PHP's stristr() function, which performs case-insensitive string searches:
<?php if ( stristr($publications, 'Daily Racing Form') ) { echo 'checked';} ?>The stristr() function searches through the $publications variable for the specified string and returns the matched portion if found, making it perfect for checking multiple selections stored in a single field.
Apply the same logic to the Elle checkbox, adapting the search string:
<input name="publications[]" type="checkbox" id="publications_elle" value="Elle" <?php if ( stristr($publications, 'Elle') ) { echo 'checked';} ?>> Elle</label>Test the complete checkbox functionality:
- Mac: localhost:8888/phpclass/update/userList.php
- Windows: localhost/phpclass/update/userList.php
Click various Edit links, paying attention to which publications each user previously selected. The checkboxes should accurately reflect their saved preferences.
Checkbox State Management Methods
| Feature | Simple Boolean | String Search |
|---|---|---|
| Use Case | Single subscription flag | Multiple publication selections |
| PHP Function | if ($subscribe) | stristr($publications, 'value') |
| Complexity | Low | Medium |
Adding a Hidden Field
Hidden fields play a crucial security and functionality role in update forms. The user ID must travel with the form data to ensure we update the correct record, but it should remain invisible and unmodifiable by users to prevent data corruption or malicious manipulation.
Return to your code editor.
In userForm.php, locate the opening
<form>tag around line 32.Add a hidden input field immediately after the form opening tag:
<form action="form-action.php" method="post" name="signup" id="signup"> <input type="hidden" name="id" value="">Populate the hidden field with the current user's ID:
<input type="hidden" name="id" value="<?php echo $id ?>">Save your changes and verify the form structure:
- Mac: localhost:8888/phpclass/update/userList.php
- Windows: localhost/phpclass/update/userList.php
Hidden fields preserve the user ID throughout the form submission process, ensuring updates target the correct record while preventing accidental user modification of critical identifiers.
Building the Update SQL
The final step involves processing the submitted form data and executing the database update. This requires careful coordination between form validation, data processing, and SQL execution.
Return to your code editor.
Open form-action.php from the update folder.
This file handles form submission, validates input data, and processes the $_POST values. It includes security measures and data sanitization that you'd find in production applications.
Navigate to line 66 and locate this comment:
//update user in databaseInclude the update processing script:
//update user in database require_once('updateUser.php');Save the file and open updateUser.php from the update folder.
This file contains the database connection logic and prepared statement framework. We need to complete the SQL statement and parameter binding.
Around line 13, find the empty $SQL variable and add the complete UPDATE statement:
$SQL = "UPDATE users SET firstName = ?, lastName = ?, email = ?, publications = ?, comments = ?, subscribe = ? WHERE id = ? ";This statement updates all user fields while using the WHERE clause to target the specific record by ID.
Around line 28, find the parameter binding comment:
//bind params hereReplace the comment with the parameter binding code:
$stmt->bind_param('ssssssi', $firstName, $lastName, $email, $publications, $comments, $subscribe, $id);Note the parameter types: six strings ('s') for text fields and one integer ('i') for the ID field. This type specification is crucial for data integrity and security.
Save your changes and test the complete update system:
- Mac: localhost:8888/phpclass/update/userList.php
- Windows: localhost/phpclass/update/userList.php
Click Edit next to any user record.
Make several changes to different form fields and click Update User. The system should return you to the user list with all changes properly saved and displayed.
Return to your code editor and close all open files—you've successfully built a complete database update system.
Complete Update Implementation
Include Update Module
Add require_once statement to connect form processing with update functionality
Write Prepared Statement
Create UPDATE SQL with placeholders for all user fields and WHERE clause
Bind Parameters
Map form variables to SQL placeholders using appropriate data types (string/integer)
Test Complete Workflow
Verify the entire process from user list through form editing to database update
You have successfully implemented a complete PHP MySQL update system with form validation, prepared statements, and proper security measures for real-world user administration.