Skip to main content
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
PDO::query
- Article
- 09/09/2022
- 2 minutes to read
In this article
Executes an SQL query and returns a result set as a PDOStatement object.
Syntax
PDOStatement PDO::query [$statement[, $fetch_style];
Parameters
$statement: The SQL statement you want to execute.
$fetch_style: The optional instructions on how to perform the query. See the Remarks section for more details. $fetch_style in PDO::query can be overridden with $fetch_style in PDO::fetch.
Return Value
If the call succeeds, PDO::query returns a PDOStatement object. If the call fails, PDO::query throws a PDOException object or returns false, depending on the setting of PDO::ATTR_ERRMODE.
Exceptions
PDOException.
Remarks
A query executed with PDO::query can execute either a prepared statement or directly, depending on the setting of PDO::SQLSRV_ATTR_DIRECT_QUERY. For more information, see Direct Statement Execution and Prepared Statement Execution in the PDO_SQLSRV Driver.
PDO::SQLSRV_ATTR_QUERY_TIMEOUT also affects the behavior of PDO::exec; for more information, see PDO::setAttribute.
You can specify the following options for $fetch_style.
PDO::FETCH_COLUMN, num | Queries for data in the specified column. The first column in the table is column 0. |
PDO::FETCH_CLASS, 'classname', array[ arglist ] | Creates an instance of a class and assigns column names to properties in the class. If the class constructor takes one or more parameters, you can also pass an arglist. |
PDO::FETCH_CLASS, 'classname' | Assigns column names to properties in an existing class. |
Call PDOStatement::closeCursor to release database resources associated with the PDOStatement object before calling PDO::query again.
You can close a PDOStatement object by setting it to null.
If all the data in a result set is not fetched, the next PDO::query call will not fail.
Support for PDO was added in version 2.0 of the Microsoft Drivers for PHP for SQL Server.
Query example
This example shows several queries.
Sql_variant example
This code sample shows how to create a table of sql_variant types and fetch the inserted data.