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
Release: 2024-11-22 07:02:14
Original
1017 people have browsed it

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("...");
    Copy after login
  2. Prepare a parameterized query statement:

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

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

    $row = $statement->fetch();
    Copy after login
  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']));
    Copy after login

Handling Exceptions

It's recommended to configure PDO to throw exceptions upon errors:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Copy after login

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!

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