SQLBuilder

Version 5 (wesen 3000, 2011-08-15 03:11 AM)

1 1
h2. SQLBuilder
2 1
3 1
This guide will show you how to use the php-activerecord SQL builder.
4 1
5 1
The first steps are to get the database connection and setup the SQL builder.
6 1
7 1
<pre class="code"><code class="php">
8 3 wesen 3000
$conn = ActiveRecord\ConnectionManager::get_connection("development");                                                                                                                         
9 1
$builder = new ActiveRecord\SQLBuilder($conn, "authors"); 
10 2 wesen 3000
</code></pre>
11 1
12 4 wesen 3000
h4(#select). SELECT queries
13 5 wesen 3000
14 2 wesen 3000
We are now ready to generate a simple SELECT query:
15 2 wesen 3000
16 2 wesen 3000
<pre class="code"><code class="php">
17 1
$builder->where("name = ?", "Hemingway");
18 1
echo $builder; /* => SELECT * FROM authors WHERE name = ? */
19 1
print_r($builder->get_where_values()); /* => array("Hemingway") */
20 3 wesen 3000
</code></pre>
21 3 wesen 3000
22 3 wesen 3000
You can also pass a hash to the where() method:
23 3 wesen 3000
24 3 wesen 3000
<pre class="code"><code class="php">
25 3 wesen 3000
$builder = new ActiveRecord\SQLBuilder($conn, "authors");                                                                                                            
26 3 wesen 3000
$builder->where(array("name" => "Hemingway",                                                                                                                         
27 3 wesen 3000
                      "country" => "USA"));
28 3 wesen 3000
echo $builder; /* => SELECT * FROM authors WHERE `name`=? AND `country`=? */
29 3 wesen 3000
print_r($builder->get_where_values()); /* => array('Hemingway', 'USA'); */
30 3 wesen 3000
31 5 wesen 3000
</code></pre>
32 5 wesen 3000
33 5 wesen 3000
You can add ordering information:
34 5 wesen 3000
35 5 wesen 3000
<pre class="code><code class="php">
36 5 wesen 3000
$builder = new ActiveRecord\SQLBuilder($conn, "authors");
37 5 wesen 3000
$builder->order('id DESC');
38 5 wesen 3000
echo $builder."\n"; /* => SELECT * FROM authors ORDER BY id DESC */
39 2 wesen 3000
</code></pre>