Home >Backend Development >PHP Tutorial >How to Perform Parameterized SELECT and INSERT Queries with PDO?

How to Perform Parameterized SELECT and INSERT Queries with PDO?

Susan Sarandon
Susan SarandonOriginal
2024-11-22 07:02:141020browse

How to Perform Parameterized SELECT and INSERT Queries with PDO?

Parameterized SELECT Queries with PDO

To perform parameterized SELECT queries with PDO, follow these steps:

  1. Create a PDO object:

    $db = new PDO("...");
  2. Prepare a parameterized query statement:

    $statement = $db->prepare("select id from some_table where name = :name");
  3. Execute the query statement, providing values for the parameters:

    $statement->execute(array(':name' => 'Jimbo'));
  4. Retrieve the results of the query:

    $row = $statement->fetch();
  5. 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!

Statement:
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