Updated to KH 3.3 and improved
This commit is contained in:
@@ -9,7 +9,6 @@ The database configuration file contains an array of configuration groups. The s
|
||||
'connection' => array CONNECTION_ARRAY,
|
||||
'table_prefix' => string TABLE_PREFIX,
|
||||
'charset' => string CHARACTER_SET,
|
||||
'profiling' => boolean QUERY_PROFILING,
|
||||
),
|
||||
|
||||
Understanding each of these settings is important.
|
||||
@@ -24,10 +23,8 @@ CONNECTION_ARRAY
|
||||
: Specific driver options for connecting to your database. (Driver options are explained [below](#connection-settings).)
|
||||
|
||||
TABLE_PREFIX
|
||||
: Prefix that will be added to all table names by the [query builder](#query_building). Prepared statements will **not** use the table prefix.
|
||||
: Prefix that will be added to all table names by the [query builder](#query_building).
|
||||
|
||||
QUERY_PROFILING
|
||||
: Enables [profiling](../kohana/profiling) of database queries. This is useful for seeing how many queries each page is using, and which are taking the longest. You must enable the profiler the view these stats.
|
||||
|
||||
## Example
|
||||
|
||||
@@ -47,7 +44,6 @@ The example file below shows 2 MySQL connections, one local and one remote.
|
||||
),
|
||||
'table_prefix' => '',
|
||||
'charset' => 'utf8',
|
||||
'profiling' => TRUE,
|
||||
),
|
||||
'remote' => array(
|
||||
'type' => 'mysql',
|
||||
@@ -60,7 +56,6 @@ The example file below shows 2 MySQL connections, one local and one remote.
|
||||
),
|
||||
'table_prefix' => '',
|
||||
'charset' => 'utf8',
|
||||
'profiling' => TRUE,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -111,8 +106,11 @@ A [PDO database](http://php.net/manual/en/book.pdo.php) can accept these options
|
||||
Type | Option | Description | Default value
|
||||
----------|------------|----------------------------| -------------------------
|
||||
`string` | dsn | PDO data source identifier | `localhost`
|
||||
`array` | options | Driver-specific options | none
|
||||
`string` | username | Database username | `NULL`
|
||||
`string` | password | Database password | `NULL`
|
||||
`boolean` | persistent | Persistent connections | `FALSE`
|
||||
|
||||
The connection character set should be configured using the DSN string or `options` array.
|
||||
|
||||
[!!] If you are using PDO and are not sure what to use for the `dsn` option, review [PDO::__construct](http://php.net/pdo.construct).
|
@@ -2,9 +2,9 @@
|
||||
|
||||
Here are some "real world" examples of using the database library to construct your queries and use the results.
|
||||
|
||||
## Examples of Prepared Statements
|
||||
## Examples of Parameterized Statements
|
||||
|
||||
TODO: 4-6 examples of prepared statements of varying complexity, including a good bind() example.
|
||||
TODO: 4-6 examples of parameterized statements of varying complexity, including a good bind() example.
|
||||
|
||||
## Pagination and search/filter
|
||||
|
||||
@@ -25,10 +25,10 @@ In this example, we loop through an array of whitelisted input fields and for ea
|
||||
|
||||
//copy the query & execute it
|
||||
$pagination_query = clone $query;
|
||||
$count = $pagination_query->select('COUNT("*") AS mycount')->execute()->get('mycount');
|
||||
$count = $pagination_query->select(DB::expr('COUNT(*)) AS mycount')->execute()->get('mycount');
|
||||
|
||||
//pass the total item count to Pagination
|
||||
$config = Kohana::config('pagination');
|
||||
$config = Kohana::$config->load('pagination');
|
||||
$pagination = Pagination::factory(array(
|
||||
'total_items' => $count,
|
||||
'current_page' => array('source' => 'route', 'key' => 'page'),
|
||||
|
@@ -1,7 +1,7 @@
|
||||
## [Database]()
|
||||
- [Configuration](config)
|
||||
- [Querying](query)
|
||||
- [Prepared Statements](query/prepared)
|
||||
- [Parameterized Statements](query/parameterized)
|
||||
- [Query Builder](query/builder)
|
||||
- [Results](results)
|
||||
- [Examples](examples)
|
@@ -1,5 +1,5 @@
|
||||
# Making Queries
|
||||
|
||||
There are two different ways to make queries. The simplest way to make a query is to use [Database_Query], via [DB::query], to manually create queries. These queries are called [prepared statements](query/prepared) and allow you to set query parameters which are automatically escaped. The second way to make a query is by building the query using method calls. This is done using the [query builder](query/builder).
|
||||
There are two different ways to make queries. The simplest way to make a query is to use [Database_Query], via [DB::query], to manually create queries. These queries are called [parameterized statements](query/parameterized) and allow you to set query parameters which are automatically escaped. The second way to make a query is by building the query using method calls. This is done using the [query builder](query/builder).
|
||||
|
||||
[!!] All queries are run using the `execute` method, which accepts a [Database] object or instance name. See [Database_Query::execute] for more information.
|
@@ -2,8 +2,6 @@
|
||||
|
||||
Creating queries dynamically using objects and methods allows queries to be written very quickly in an agnostic way. Query building also adds identifier (table and column name) quoting, as well as value quoting.
|
||||
|
||||
[!!] At this time, it is not possible to combine query building with prepared statements.
|
||||
|
||||
## Select
|
||||
|
||||
Each type of database query is represented by a different class, each with their own methods. For instance, to create a SELECT query, we use [DB::select] which is a shortcut to return a new [Database_Query_Builder_Select] object:
|
||||
@@ -38,7 +36,7 @@ By default, [DB::select] will select all columns (`SELECT * ...`), but you can a
|
||||
|
||||
Now take a minute to look at what this method chain is doing. First, we create a new selection object using the [DB::select] method. Next, we set table(s) using the `from()` method. Last, we search for a specific records using the `where()` method. We can display the SQL that will be executed by casting the query to a string:
|
||||
|
||||
echo Kohana::debug((string) $query);
|
||||
echo Debug::vars((string) $query);
|
||||
// Should display:
|
||||
// SELECT `username`, `password` FROM `users` WHERE `username` = 'john'
|
||||
|
||||
@@ -150,11 +148,11 @@ This query would generate the following SQL:
|
||||
|
||||
### Database Functions
|
||||
|
||||
Eventually you will probably run into a situation where you need to call `COUNT` or some other database function within your query. The query builder supports these functions in two ways. The first is by using quotes within aliases:
|
||||
Eventually you will probably run into a situation where you need to call `COUNT` or some other database function within your query. The query builder supports these functions using the `Database_Expression` class:
|
||||
|
||||
$query = DB::select(array('COUNT("username")', 'total_users'))->from('users');
|
||||
$query = DB::select(array(DB::expr('COUNT(`username`)'), 'total_users'))->from('users');
|
||||
|
||||
This looks almost exactly the same as a standard `AS` alias, but note how the column name is wrapped in double quotes. Any time a double-quoted value appears inside of a column name, **only** the part inside the double quotes will be escaped. This query would generate the following SQL:
|
||||
This looks almost exactly the same as a standard `AS` alias, but note how the column name is put in a call to `DB::expr()`. Any time `DB::expr()` is used, the column name will **not** be escaped. This query would generate the following SQL:
|
||||
|
||||
SELECT COUNT(`username`) AS `total_users` FROM `users`
|
||||
|
||||
@@ -166,14 +164,14 @@ This looks almost exactly the same as a standard `AS` alias, but note how the co
|
||||
->where('posts.created', '>=', $yesterday);
|
||||
|
||||
$total = clone $query;
|
||||
$total->select(array('COUNT( DISTINCT "username")', 'unique_users'));
|
||||
$total->select(array(DB::expr('COUNT( DISTINCT `username`)'), 'unique_users'));
|
||||
$query->select('posts.username')->distinct();
|
||||
|
||||
### Aggregate Functions
|
||||
|
||||
Aggregate functions like `COUNT()`, `SUM()`, `AVG()`, etc. will most likely be used with the `group_by()` and possibly the `having()` methods in order to group and filter the results on a set of columns.
|
||||
|
||||
$query = DB::select('username', array('COUNT("id")', 'total_posts')
|
||||
$query = DB::select('username', array(DB::expr('COUNT(`id`)'), 'total_posts')
|
||||
->from('posts')->group_by('username')->having('total_posts', '>=', 10);
|
||||
|
||||
This will generate the following query:
|
||||
@@ -184,7 +182,7 @@ This will generate the following query:
|
||||
|
||||
Query Builder objects can be passed as parameters to many of the methods to create subqueries. Let's take the previous example query and pass it to a new query.
|
||||
|
||||
$sub = DB::select('username', array('COUNT("id")', 'total_posts')
|
||||
$sub = DB::select('username', array(DB::expr('COUNT(`id`)'), 'total_posts')
|
||||
->from('posts')->group_by('username')->having('total_posts', '>=', 10);
|
||||
|
||||
$query = DB::select('profiles.*', 'posts.total_posts')->from('profiles')
|
||||
@@ -198,7 +196,7 @@ This will generate the following query:
|
||||
|
||||
Insert queries can also use a select query for the input values
|
||||
|
||||
$sub = DB::select('username', array('COUNT("id")', 'total_posts')
|
||||
$sub = DB::select('username', array(DB::expr('COUNT(`id`)'), 'total_posts')
|
||||
->from('posts')->group_by('username')->having('total_posts', '>=', 10);
|
||||
|
||||
$query = DB::insert('post_totals', array('username', 'posts'))->select($sub);
|
||||
|
@@ -1,6 +1,6 @@
|
||||
# Prepared Statements
|
||||
# Parameterized Statements
|
||||
|
||||
Using prepared statements allows you to write SQL queries manually while still escaping the query values automatically to prevent [SQL injection](http://wikipedia.org/wiki/SQL_Injection). Creating a query is simple:
|
||||
Using parameterized statements allows you to write SQL queries manually while still escaping the query values automatically to prevent [SQL injection](http://wikipedia.org/wiki/SQL_Injection). Creating a query is simple:
|
||||
|
||||
$query = DB::query(Database::SELECT, 'SELECT * FROM users WHERE username = :user');
|
||||
|
||||
@@ -50,9 +50,9 @@ The only difference between `param()` and `bind()` is that `bind()` passes the v
|
||||
|
||||
## Display the raw query
|
||||
|
||||
If you want to display the SQL that will be executed, simply cast the object to a string:
|
||||
If you want to display the SQL that will be executed, you can simply echo the query:
|
||||
|
||||
echo Kohana::debug((string) $query);
|
||||
echo $query;
|
||||
// Should display:
|
||||
// SELECT * FROM users WHERE username = 'john'
|
||||
|
@@ -2,7 +2,7 @@
|
||||
|
||||
## Execute
|
||||
|
||||
Once you have a query object built, either through a prepared statement or through the builder, you must then `execute()` the query and retrieve the results. Depending on the query type used, the results returned will vary.
|
||||
Once you have a query object built, either through a parameterized statement or through the builder, you must then `execute()` the query and retrieve the results. Depending on the query type used, the results returned will vary.
|
||||
|
||||
## Select
|
||||
|
||||
@@ -70,7 +70,7 @@ To return a non-associative array, leave `$key` as NULL and just pass a `$value`
|
||||
|
||||
Sometime you only want a single value from a query. The `get()` method returns the value of the named column from the current row. The second parameter, `$default`, is used to supply a default value when the result is NULL.
|
||||
|
||||
$total_users = DB::select(array('COUNT("username")', 'total_users'))->from('users')->execute()->get('total_users', 0);
|
||||
$total_users = DB::select(array(DB::expr('COUNT(`username`)'), 'total_users'))->from('users')->execute()->get('total_users', 0);
|
||||
|
||||
### Select - `cached()`
|
||||
|
||||
|
Reference in New Issue
Block a user