PDO: Parameterized SELECT Query for Table ID Retrieval
In this scenario, we seek to retrieve the ID from a table based on a name parameter and determine the success of an INSERT operation using that ID.
To accomplish this using a parameterized SELECT query with PDO, follow these steps:
$db = new PDO("...");
$statement = $db->prepare("SELECT id FROM some_table WHERE name = :name");
$statement->execute([':name' => "Jimbo"]);
$row = $statement->fetch(); $id = $row['id'];
$statement = $db->prepare("INSERT INTO some_other_table (some_id) VALUES (:some_id)");
$statement->execute([':some_id' => $id]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
By following these steps, you can efficiently perform a parameterized SELECT query and use the retrieved ID for a subsequent INSERT operation in another table.
The above is the detailed content of How to Retrieve a Table ID via Parameterized SELECT and Use It for an INSERT with PDO?. For more information, please follow other related articles on the PHP Chinese website!