DB::query (method)

Last updated: Tue, Oct 31, 2023 1:43 pm
Return to Knowledgebase


Execute a SQL query with optional parameters.




# Parameter Data Type Required Description
1 $sql string Yes The SQL query to be executed
2 $params = array array Yes An array of parameters to be bound to the prepared statement.


Data Type Description of Returned Data
nothing Captures the results of the query and relevant information such as the number of rows affected and the last inserted ID


$result = $db->query("SELECT * FROM users");

Further Documentation:

1. Increments the query count for tracking purposes.
2. Initializes variables related to error handling, results, count, and last insert ID.
3. Prepares the SQL statement using the PDO prepare method.
4. Binds parameters to the prepared statement if any are provided.
5. Attempts to execute the query and handles any exceptions that may occur during the execution.
6. If executed successfully, it fetches the results as an array of objects and converts them to an associative array. It also retrieves the count of rows affected and the last inserted ID.
7. If an exception is caught during execution, it sets the error flag to true and retrieves the error information.

// Example 1: Execute a simple SQL query
$db = new DB();
$result = $db->query("SELECT * FROM users");

// Example 2: Execute a parameterized SQL query
$result = $db->query("SELECT * FROM users WHERE id = ? AND name = ?", [1, 'John']);