If there is a PHP installed on the machine you are using, you can write a PHP script to do that. It requires the PHP installation has the mysql extension installed.
You can call PHP interpreter from the command line like so
php --php-ini path/to/php.ini your-script.php
I am including the --php-ini switch, because you may need to use your own php config that enables the mysql extension. On PHP 5.3.0+ that extension is enabled by default, so that is no longer necessary to use the config to enable it.
Then you can write your export script like any normal PHP script.
<?php
#mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$result = mysql_query("SELECT * FROM table_with_the_data p WHERE p.type = $typeiwant");
$result || die(mysql_error());
while($row = mysql_fetch_row($result)) {
$comma = false;
foreach ($row as $item) {
#make it comma separated
if ($comma) {
echo ',';
} else {
$comma = true;
}
#quiote the quiotes
$quoted = str_replace("\"", "\"\"", $item);
#quiote the string
echo "\"$quoted\"";
}
echo "\n";
}
?>
The advantage of this method is, that it has no problems with varchar and text fields, that have text containing newlines. Those fields are correctly quioted and those newlines in them will be interpreted by the CSV reader as a part of the text, not record separators. That is something that is hard to correct afterwards with sed or so.
REPLACE()
in your query to have the quotes escaped. – dsm Dec 10 '08 at 16:08