In SQL Server, you can send emails using the sp_send_dbmail stored procedure in the msdb database.
One of the choices you have when executing this procedure is whether or not to include the results of a query.
Another choice you have is whether or not to send those results in an attachment.
Example
To email the results of a query, use the @query argument.
To attach those results as an attachment, use the @attach_query_result_as_file argument. This is accepts a bit value, with the default being 0 (for no attachment).
To send the results in an attachment, simply provide a 1 for this argument.
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'DB Admin Profile', @recipients = '[email protected]', @body = 'Potential candidates for an Admin job, perhaps?', @query = 'SELECT TOP(5) * FROM Artists;', @execute_query_database = 'Music', @attach_query_result_as_file = 1, @subject = 'Query results as discussed';This example sends an email with the results attached as a .txt file. The name was automatically generated by Database Mail.
By default, the maximum file size for attachments is 1 MB per file, but you can change this with the sysmail_configure_sp stored procedure.
Provide a Name for the Attachment
You also have the option of providing your own name for the attachment. You can do this with the @query_attachment_filename argument.
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'DB Admin Profile', @recipients = '[email protected]', @body = 'Potential candidates for an Admin job, perhaps?', @query = 'SELECT TOP(5) * FROM Artists;', @execute_query_database = 'Music', @attach_query_result_as_file = 1, @query_attachment_filename = 'Artists.csv', @subject = 'Query results as discussed';More Options
Here’s another example that expands on the previous one. Here, I’ve included a number of options that you might find useful when sending query results as an email attachment.
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'DB Admin Profile', @recipients = '[email protected]', @body = 'Potential candidates for an Admin job, perhaps?', @query = 'SELECT TOP(5) * FROM Artists;', @execute_query_database = 'Music', @attach_query_result_as_file = 1, @query_attachment_filename = 'Artists.csv', @query_result_header = 1, @query_result_width = 256, @query_result_separator = ',', @exclude_query_output = 1, @append_query_error = 1, @query_no_truncate = 0, @query_result_no_padding = 1, @subject = 'Query results as discussed';Some of these are set to their default value and some aren’t. For example, I’ve changed @query_result_no_padding to 1 in order to remove padding from within the columns. I’ve also used @query_result_separator to change the separator from the default space, to a comma.
The sp_send_dbmail procedure accepts more arguments than I’ve listed here. See Microsoft’s documentation for a full list of arguments and their descriptions.
Configuring Database Mail
The examples on this page assume that you’ve already enabled and configured Database Mail.
If you don’t have Database Mail configured, see How to Send Email from SQL Server. That article provides examples for enabling and configuring Database Mail with T-SQL.
There are several ways to generate query results: This method 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: <?php
$query = $db->query('YOUR QUERY');
foreach ($query->getResult() as $row) {
echo $row->title;
echo $row->name;
echo $row->body;
}
The above method is an alias of getResultObject(). You can
pass in the string ‘array’ if you wish to get your results as an array of arrays: <?php
$query = $db->query('YOUR QUERY');
foreach ($query->getResult('array') as $row) {
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
The above usage is an alias of getResultArray(). You can also pass a string to getResult() which represents a class to instantiate for each result object <?php
$query = $db->query('SELECT * FROM users;');
foreach ($query->getResult('User') as $user) {
echo $user->name; // access attributes
echo $user->reverseName(); // or methods defined on the 'User' class
}
The above method is an alias of getCustomResultObject(). This method 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: <?php
$query = $db->query('YOUR QUERY');
foreach ($query->getResultArray() as $row) {
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
This
method returns a single result row. If your query has more than one row, it returns only the first row. The result is returned as an object. Here’s a usage example: <?php
$query = $db->query('YOUR QUERY');
$row = $query->getRow();
if (isset($row)) {
echo $row->title;
echo $row->name;
echo $row->body;
}
If you want a specific row returned you can submit the row number as a digit in the first parameter: <?php
$row = $query->getRow(5);
You can also add a second String parameter, which is the name of a class to instantiate the row with: <?php
$query = $db->query('SELECT * FROM users LIMIT 1;');
$row = $query->getRow(0, 'User');
echo $row->name; // access attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
Identical to the above row() method, except it returns an array. Example: <?php
$query = $db->query('YOUR QUERY');
$row = $query->getRowArray();
if (isset($row)) {
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
If you want a specific row returned you can submit the row number as a digit in the first parameter: <?php
$row = $query->getRowArray(5);
Result Arrays
getResult()
getResultArray()
Result Rows
getRow()
getRowArray()
In addition, you can walk forward/backwards/first/last through your results using these variations:
$row = $query->getFirstRow()
$row = $query->getLastRow()
$row = $query->getNextRow()
$row = $query->getPreviousRow()
By default they return an object unless you put the word “array” in the parameter:
$row = $query->getFirstRow('array')
$row = $query->getLastRow('array')
$row = $query->getNextRow('array')
$row = $query->getPreviousRow('array')
Note
All the methods above will load the whole result into memory (prefetching). Use getUnbufferedRow() for processing large result sets.
getUnbufferedRow()
This method returns a single result row without prefetching the whole result in memory as row() does. If your query has more than one row, it returns the current row and moves the internal data pointer ahead.
<?php $query = $db->query('YOUR QUERY'); while ($row = $query->getUnbufferedRow()) { echo $row->title; echo $row->name; echo $row->body; }
For use with MySQLi you may set MySQLi’s result mode to MYSQLI_USE_RESULT for maximum memory savings. Use of this is not generally recommended but it can be beneficial in some circumstances such as writing large queries to csv. If you change the result mode be aware of the tradeoffs associated with it.
<?php $db->resultMode = MYSQLI_USE_RESULT; // for unbuffered results $query = $db->query('YOUR QUERY'); $file = new \CodeIgniter\Files\File(WRITEPATH . 'data.csv'); $csv = $file->openFile('w'); while ($row = $query->getUnbufferedRow('array')) { $csv->fputcsv($row); } $db->resultMode = MYSQLI_STORE_RESULT; // return to default mode
Note
When using MYSQLI_USE_RESULT all subsequent calls on the same connection will result in error until all records have been fetched or a freeResult() call has been made. The getNumRows() method will only return the number of rows based on the current position of the data pointer. MyISAM tables will remain locked until all the records have been fetched or a freeResult() call has been made.
You can optionally pass ‘object’ (default) or ‘array’ in order to specify the returned value’s type:
<?php $query->getUnbufferedRow(); // object $query->getUnbufferedRow('object'); // object $query->getUnbufferedRow('array'); // associative array
Custom Result Objects
You can have the results returned as an instance of a custom class instead of a stdClass or array, as the getResult() and getResultArray() methods allow. If the class is not already loaded into memory, the Autoloader will attempt to load it. The object will have all values returned from the database set as properties. If these have been declared and are non-public then you should provide a __set() method to allow them to be set.
Example:
<?php class User { public $id; public $email; public $username; protected $last_login; public function lastLogin($format) { return $this->lastLogin->format($format); } public function __set($name, $value) { if ($name === 'lastLogin') { $this->lastLogin = DateTime::createFromFormat('!U', $value); } } public function __get($name) { if (isset($this->{$name})) { return $this->{$name}; } } }
In addition to the two methods listed below, the following methods also can take a class name to return the results as: getFirstRow(), getLastRow(), getNextRow(), and getPreviousRow().
getCustomResultObject()
Returns the entire result set as an array of instances of the class requested. The only parameter is the name of the class to instantiate.
Example:
<?php $query = $db->query('YOUR QUERY'); $rows = $query->getCustomResultObject('User'); foreach ($rows as $row) { echo $row->id; echo $row->email; echo $row->last_login('Y-m-d'); }
getCustomRowObject()
Returns a single row from your query results. The first parameter is the row number of the results. The second parameter is the class name to instantiate.
Example:
<?php $query = $db->query('YOUR QUERY'); $row = $query->getCustomRowObject(0, 'User'); if (isset($row)) { echo $row->email; // access attributes echo $row->last_login('Y-m-d'); // access class methods }
You can also use the getRow() method in exactly the same way.
Example:
<?php $row = $query->getCustomRowObject(0, 'User');
Result Helper Methods
getFieldCount()
The number of FIELDS (columns) returned by the query. Make sure to call the method using your query result object:
<?php $query = $db->query('SELECT * FROM my_table'); echo $query->getFieldCount();
getFieldNames()
Returns an array with the names of the FIELDS (columns) returned by the query. Make sure to call the method using your query result object:
<?php $query = $db->query('SELECT * FROM my_table'); echo $query->getFieldNames();
getNumRows()
The number of records returned by the query. Make sure to call the method using your query result object:
<?php $query = $db->query('SELECT * FROM my_table'); echo $query->getNumRows();
Note
Because SQLite3 lacks an efficient method returning a record count, CodeIgniter will fetch and buffer the query result records internally and return a count of the resulting record array, which can be inefficient.
freeResult()
It frees the memory associated with the result and deletes the result resource ID. Normally PHP frees its memory automatically at the end of script execution. However, if you are running a lot of queries in a particular script you might want to free the result after each query result has been generated in order to cut down on memory consumption.
Example:
<?php $query = $thisdb->query('SELECT title FROM my_table'); foreach ($query->getResult() as $row) { echo $row->title; } $query->freeResult(); // The $query result object will no longer be available $query2 = $db->query('SELECT name FROM some_table'); $row = $query2->getRow(); echo $row->name; $query2->freeResult(); // The $query2 result object will no longer be available
dataSeek()
This method sets the internal pointer for the next result row to be fetched. It is only useful in combination with getUnbufferedRow().
It accepts a positive integer value, which defaults to 0 and returns true on success or false on failure.
<?php $query = $db->query('SELECT `field_name` FROM `table_name`'); $query->dataSeek(5); // Skip the first 5 rows $row = $query->getUnbufferedRow();
Note
Not all database drivers support this feature and will return false. Most notably - you won’t be able to use it with PDO.
Class Reference
class CodeIgniter\Database\BaseResult getResult([$type = 'object'])
|
Array containing the fetched rows |
array |
A wrapper for the getResultArray(), getResultObject() and getCustomResultObject() methods.
Usage: see Result Arrays.
getResultArray()Array containing the fetched rows |
array |
Returns the query results as an array of rows, where each row is itself an associative array.
Usage: see Result Arrays.
getResultObject()Array containing the fetched rows |
array |
Returns the query results as an array of rows, where each row is an object of type stdClass.
Usage: see Result Arrays.
getCustomResultObject($class_name)
|
Array containing the fetched rows |
array |
Returns the query results as an array of rows, where each row is an instance of the specified class.
getRow([$n = 0[, $type = 'object']])
|
The requested row or null if it doesn’t exist |
mixed |
A wrapper for the getRowArray(), getRowObject() and getCustomRowObject() methods.
Usage: see Result Rows.
|
Next row from the result set or null if it doesn’t exist |
mixed |
Fetches the next result row and returns it in the requested form.
Usage: see Result Rows.
getRowArray([$n = 0])
|
The requested row or null if it doesn’t exist |
array |
Returns the requested result row as an associative array.
Usage: see Result Rows.
getRowObject([$n = 0])
|
stdClass |
Returns the requested result row as an object of type stdClass.
Usage: see Result Rows.
getCustomRowObject($n, $type)
|
The requested row or null if it doesn’t exist |
$type |
Returns the requested result row as an instance of the requested class.
dataSeek([$n = 0])
|
true on success, false on failure |
bool |
Moves the internal results row pointer to the desired offset.
Usage: see Result Helper Methods.
setRow($key[, $value = null])
|
void |
Assigns a value to a particular column.
getNextRow([$type = 'object'])
|
Next row of result set, or null if it doesn’t exist |
mixed |
Returns the next row from the result set.
getPreviousRow([$type = 'object'])
|
Previous row of result set, or null if it doesn’t exist |
mixed |
Returns the previous row from the result set.
getFirstRow([$type = 'object'])
|
First row of result set, or null if it doesn’t exist |
mixed |
Returns the first row from the result set.
getLastRow([$type = 'object'])
|
Last row of result set, or null if it doesn’t exist |
mixed |
Returns the last row from the result set.
getFieldCount()Number of fields in the result set |
int |
Returns the number of fields in the result set.
Usage: see Result Helper Methods.
getFieldNames()Array of column names |
array |
Returns an array containing the field names in the result set.
getFieldData()Array containing field meta-data |
array |
Generates an array of stdClass objects containing field meta-data.
getNumRows()Number of rows in result set |
int |
Returns number of rows returned by the query
freeResult()void |
Frees a result set.
Usage: see Result Helper Methods.