summaryrefslogtreecommitdiffstats
path: root/system/database
diff options
context:
space:
mode:
Diffstat (limited to 'system/database')
-rw-r--r--system/database/DB_utility.php54
1 files changed, 35 insertions, 19 deletions
diff --git a/system/database/DB_utility.php b/system/database/DB_utility.php
index d48425d7e..8ce19b17f 100644
--- a/system/database/DB_utility.php
+++ b/system/database/DB_utility.php
@@ -236,35 +236,51 @@ class CI_DB_utility {
* @param string The newline character - \n by default
* @return string
*/
- function csv_from_result($query, $delim = "\t", $newline = "\n")
+ function csv_from_result($query, $delim = ',', $newline = '', $enclosure = '"')
{
- if ( ! is_object($query) OR ! method_exists($query, 'field_names'))
- {
- show_error('You must submit a valid result object');
- }
+ if (!is_a($query, 'CI_DB_result')) {
+ show_error('CI_DB_utility::csv_from_result - You must submit a valid result object');
+ }
+
+ if ($delim === '') {
+ show_error('CI_DB_utility::csv_from_result - Empty delimiters are not permitted');
+ }
+
+ if ($newline === '') {
+ $newline = (stripos(getenv('HTTP_USER_AGENT'), 'win') !== false) ? "\r\n" : "\n";
+ }
+ if ((strpos($enclosure, $newline) !== false) or (($enclosure !== '') and (strpos($newline, $enclosure) !== false))) {
+ show_error('CI_DB_utility::csv_from_result - Field enclosure must not be contained within delimiter (or vice versa)');
+ }
+
$out = '';
// First generate the headings from the table column names
- foreach ($query->list_fields() as $name)
- {
- $out .= $name.$delim;
+ foreach ($query->list_fields() as $name) {
+ // there's no point enclosing strings that do not require it
+ if (strpos($name, $delim) !== false) {
+ $out .= $enclosure . $name . $enclosure . $delim;
+ } else {
+ $out .= $name . $delim;
+ }
}
- $out = rtrim($out);
- $out .= $newline;
-
+ $out = rtrim($out, $delim) . $newline;
+
// Next blast through the result array and build out the rows
- foreach ($query->result_array() as $row)
- {
- foreach ($row as $item)
- {
- $out .= $item.$delim;
+ foreach ($query->result_array() as $row) {
+ foreach ($row as $item) {
+ // there's no point enclosing strings that do not require it
+ if (strpos($item, $delim) !== false) {
+ $out .= $enclosure . $item . $enclosure . $delim;
+ } else {
+ $out .= $item . $delim;
+ }
}
- $out = rtrim($out);
- $out .= $newline;
+ $out = rtrim($out, $delim) . $newline;
}
-
+
return $out;
}