summaryrefslogtreecommitdiffstats
path: root/system
diff options
context:
space:
mode:
authorDerek Allard <derek.allard@ellislab.com>2007-07-12 14:36:50 +0200
committerDerek Allard <derek.allard@ellislab.com>2007-07-12 14:36:50 +0200
commit7dcd7a3aa4b145fc8a040c16e7c4de9ea35fd5cf (patch)
tree78bf0a4b2d92250a76740a3e2762312c8bf593e6 /system
parentc9e2b10f08a3c718e52e287e2dd14b880e4e3057 (diff)
csv_from_result() move robust against data with "," in it.
Diffstat (limited to 'system')
-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;
}