Once we have the table structure ready, the next step is inserting data. At this stage, we must be extremely careful about security, as SQL injections are one of the most common vulnerabilities in web applications.
In the example below, we will use PDO (PHP Data Objects) and so-called "Prepared Statements." This method ensures that the data being entered is treated separately from the SQL command itself, making malicious attacks impossible.
Key steps of the process:
- Establishing a secure connection to the database.
- Preparing the SQL statement using question marks (?) as placeholders.
- Binding actual values to these placeholders.
- Executing the command and verifying success.
Here is a practical code example that inserts test data into the stranke table:
// Preparing the SQL statement (without direct data!)
$sql = "INSERT INTO stranke (first_name, last_name, address, house_number, city, zip_code)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
// Execution by inserting data
$stmt->execute(['Sarah', 'Jenkins', 'Oak Avenue', '42', 'Bristol', 'BS1 4ND']);
By using PDO, your programming becomes more professional, and your code more readable and secure against external intrusions.
Want to become a database master?
If you want to learn more about all the tricks and
advanced features, visit my full
PDO tutorial.