Parameterized SELECT Queries with PDO
To perform parameterized SELECT queries with PDO, follow these steps:
Create a PDO object:
$db = new PDO("...");
Prepare a parameterized query statement:
$statement = $db->prepare("select id from some_table where name = :name");
Execute the query statement, providing values for the parameters:
$statement->execute(array(':name' => 'Jimbo'));
Retrieve the results of the query:
$row = $statement->fetch();
To insert into another table, prepare and execute another parameterized query statement:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)"); $statement->execute(array(':some_id' => $row['id']));
Handling Exceptions
It's recommended to configure PDO to throw exceptions upon errors:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
This way, any errors during query execution will be caught as PDOExceptions.
The above is the detailed content of How to Perform Parameterized SELECT and INSERT Queries with PDO?. For more information, please follow other related articles on the PHP Chinese website!