Home >Database >Mysql Tutorial >Why Doesn't My PDO INSERT INTO Prepared Statement Work?
PHP Data Objects (PDO) offers prepared statements for secure MySQL interaction, but constructing INSERT INTO
queries can be challenging. Let's address a common issue and its solution.
Consider this code:
<code class="language-php">$statement = $link->prepare("INSERT INTO testtable(name, lastname, age) VALUES('Bob','Desaunois','18')"); $statement->execute();</code>
This seemingly correct code often fails to populate the database. Why?
The key is parameter binding. This prevents SQL injection vulnerabilities and improves code maintainability. Instead of directly embedding values, PDO uses placeholders:
:name
in the SQL and provide values in an associative array to execute()
.?
as placeholders and supply values in a numerically indexed array to execute()
.Here's the corrected code using named parameters:
<code class="language-php">$statement = $link->prepare("INSERT INTO testtable(name, lastname, age) VALUES (:name, :lastname, :age)"); $statement->execute([ 'name' => 'Bob', 'lastname' => 'Desaunois', 'age' => '18', ]);</code>
And here's the equivalent using positional parameters:
<code class="language-php">$statement = $link->prepare("INSERT INTO testtable(name, lastname, age) VALUES (?, ?, ?)"); $statement->execute(['Bob', 'Desaunois', '18']);</code>
Parameter binding enhances database security and makes your code more efficient and readable. It's essential for robust PDO usage. Mastering this technique is crucial for secure and effective PHP database programming.
The above is the detailed content of Why Doesn't My PDO INSERT INTO Prepared Statement Work?. For more information, please follow other related articles on the PHP Chinese website!