Home > Backend Development > PHP Tutorial > How to Properly Use PDO Prepared Statements for INSERT INTO Queries in MySQL?

How to Properly Use PDO Prepared Statements for INSERT INTO Queries in MySQL?

Linda Hamilton
Release: 2024-11-29 13:15:11
Original
1040 people have browsed it

How to Properly Use PDO Prepared Statements for INSERT INTO Queries in MySQL?

PDO with INSERT INTO through prepared statements

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template