--- title: 'PostgreSQL PHP: Querying Data' page_title: 'PostgreSQL PHP: Queying Data From PostgreSQL Tables' page_description: 'In this tutorial, you will step by step learn how to query data from the tables in the PostgreSQL database using PHP PDO.' prev_url: 'https://www.postgresqltutorial.com/postgresql-php/query/' ogImage: '/postgresqltutorial/PostgreSQL-PHP-Query-Example.png' updatedOn: '2022-02-09T14:55:54+00:00' enableTableOfContents: true previousLink: title: 'PostgreSQL PHP: Updating Data In a Table' slug: 'postgresql-php/update' nextLink: title: 'PostgreSQL PHP: Transaction' slug: 'postgresql-php/transaction' --- **Summary**: in this tutorial, you will learn to query data from the PostgreSQL database in PHP using PDO. ## Querying all rows in a table To query all rows from a table in the PostgreSQL database, you use the following steps: 1. First, [connect to the PostgreSQL database](connect) by creating a new PDO object. 2. Second, call the `query()` method of the PDO object. The query() method accepts a [SELECT](../postgresql-tutorial/postgresql-select) statement as the argument. The query method returns a `PDOStatement` object. 3. Third, fetch the next rows from the result by calling the fetch() method of the PDOstatement object. The fetch_style argument of the `fetch()` method controls how the result returned. For example, the `PDO::FETCH_ASSOC` instructs the `fetch()` method to return the result set as an array indexed by column name. We will use the `stocks` table created in the [creating table tutorial](create-tables) for the demonstration. Let’s create a new class `StockDB` for storing all the methods that select data from the `stocks` table. The following `all()` method selects all rows in the `stocks` table. ```phpsql /** * Return all rows in the stocks table * @return array */ public function all() { $stmt = $this->pdo->query('SELECT id, symbol, company ' . 'FROM stocks ' . 'ORDER BY symbol'); $stocks = []; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $stocks[] = [ 'id' => $row['id'], 'symbol' => $row['symbol'], 'company' => $row['company'] ]; } return $stocks; } ``` To test the `all()` method, we use the following code in the `index.php` file.  ```php connect(); // $stockDB = new StockDB($pdo); // get all stocks data $stocks = $stockDB->all(); } catch (\PDOException $e) { echo $e->getMessage(); } ?>
| ID | Symbol | Company |
|---|---|---|