Home >Backend Development >PHP Tutorial >How to Properly Use PDO Prepared Statements for INSERT INTO Queries in MySQL?
Executing MySQL queries through prepared statements can be a bit tricky when working with PDO. Let's dive into the issue presented and uncover the solution:
In the provided code, the INSERT INTO statement is constructed using the prepare() method, which prepares the statement but does not execute it. To actually execute the query and insert the data, the execute() method must be called.
Additionally, when using prepared statements with PDO, it's essential to use placeholders (e.g., :name, :lastname) in the SQL query instead of embedding the values directly. Placeholders allow you to bind the values to the prepared statement later. This approach enhances security by preventing SQL injection vulnerabilities.
The corrected code should look like this:
$dbhost = "localhost"; $dbname = "pdo"; $dbusername = "root"; $dbpassword = "845625"; $link = new PDO("mysql:host=$dbhost;dbname=$dbname", "$dbusername", "$dbpassword"); $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set error mode to exception $statement = $link->prepare("INSERT INTO testtable(name, lastname, age) VALUES(:name, :lastname, :age)"); $statement->bindParam(':name', 'Bob'); $statement->bindParam(':lastname', 'Desaunois'); $statement->bindParam(':age', 18); $statement->execute();
By using placeholders and binding the values using bindParam(), the query is properly executed and the data is inserted into the database. Prepared statements help prevent SQL injection and ensure the integrity of your data.
The above is the detailed content of How to Properly Use PDO Prepared Statements for INSERT INTO Queries in MySQL?. For more information, please follow other related articles on the PHP Chinese website!