Professional CodeIgniter

(singke) #1

Chapter 3: A 10,000 - Foot View of CodeIgniter


$Q = $this- > db- > query($sql);

$row = $Q- > row();
echo $row- > id;

//alternative syntax
$row = $Q- > row_array();
echo $row[‘id’];

Using this method allows you to pass any SQL query you want to the database, including inserts,
updates, and deletes:

$sql = “insert into persons (name, gender, age)
values (‘Tom Myer’, ‘male’,35)”;

$this- > db- > query($sql);

A more secure way of handling this kind of query is to use query binding:

$sql = “insert into persons (name, gender, age)

$this- > db- > query($sql, array(“Tom”,”male”,35));

Why is this method more secure? The query binding automatically escapes whatever data you pass
through, eliminating potential security problems. In this book, however, very few raw queries are run, as
most work is done via the Active Record class. In Chapter 9 , where you learn more about security,
database security is among the topics covered.

At some point, though, you ’ ll want to take advantage of some of the Active Record patterns that
CodeIgniter makes available to you. Each pattern allows you to interact with a database table with
minimal scripting. This is good not only from a “ conservation of typing ” point of view; it also makes
your database code more portable between database types.

For example, this is how you would retrieve all the database records from the persons table:

$Q = $this- > db- > get(‘persons’);

If you want to limit how many records to retrieve from the persons table, you would do the following:

$Q = $this- > db- > get(‘persons’,5,20);
//query would become:
//select * from persons limit 20, 5
//and would show five records after an offset of 20 (records 21 - 25)

If you want to limit which fields are selected in your query, use the select() method first:

$this- > db- > select(‘id, name, gender’);
$Q = $this- > db- > get(‘persons’);
Free download pdf