Download CodeIgniter 2.1.2 User Guide

Transcript
197 z 264
The secondary benefit of using binds is that the values are automatically escaped, producing safer
queries. You don't have to remember to manually escape data; the engine does it automatically for
you.
Generating Query Results
There are several ways to generate query results:
result()
This function returns the query result as an array of objects, or an empty array on failure.
Typically you'll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
The above function is an alias of result_object().
If you run queries that might not produce a result, you are encouraged to test the result first:
$query = $this->db->query("YOUR QUERY");
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
}
You can also pass a string to result() which represents a class to instantiate for each result object
(note: this class must be loaded)
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $row)
{
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
result_array()
This function returns the query result as a pure array, or an empty array when no result is produced.
Typically you'll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
2012-07-10 19:53