Export the result of MySQL query to my PC as a CSV file - mysql

I would like to export some MySQL-query results to my PC as a CSV-file. According to some contributions in the internet (e.g. here) it should work like the following:
mysql> SELECT 1,2,3,4,5 INTO OUTFILE 'C:\Users\MyPC\Desktop\numbers.csv';
ERROR 1 (HY000): Can't create/write to file 'C:\Users\MyPC\Desktop\numbers.csv' (Errorcode: 22 Invalid argument)
But theat leads to the given error. Waht am I doing wrong here? How can I save the output of my query as a csv ot a txt file?
P.S.: Im am using Windows

First of all, you didn't mention FROM which database you want the entrys.
SELECT 1,2,3,4,5 FROM ??????????????? INTO ...
With PHP you can do it like this:
$dz=fopen("file.csv", "w+");
$sql = "SELECT 1,2,3,4,5 FROM ?????????";
if ($result = $connectiontodatabase->query($sql)) {
while ($row = $result->fetch_assoc()) {
fputs($dz, $row['1'] . "\t" . $row['2'] . "\t" . $row['3' . "\t" . $row['4'] . "\t" . $row['5'] . "\t\n");
}}
fclose($dz);
$connectiontodatabase of course needs to be the new mysqli statement

Related

CSV Import file formatting for prestashop products

I'm trying to import items with CSV - in the 'customizable' column it says "(0 = No, 1 = Yes)".
I've read a few other threads about this and it looks like it should be formatted like this:
"Field 1"|1, "Field 2"|1
But when I try to upload the products with that syntax in the customizable column - it fails the import.
If I change it to just 1 or 0, the upload succeeds; but then I have to go into each product, then click on customization, then click on customization text and save it (which is what I'm trying to avoid with the CSV in the first place).
What is the appropriate way to format the upload CSV so that the customizable fields save appropriately?
I'm using 1.6.1.4.
Well unfortunately it doesn't look like it's an option by the default CSV import (which is a bummer).
I was able to solve it by writing a small script to adjust the database.
The script looks like this:
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
echo "Connected successfully<br /><br />";
$conn->query("update ps_category_lang set name=SUBSTRING_INDEX(name, '(', 1) WHERE name REGEXP '([[:digit:]]+)';");
$conn->query("truncate table ps_customization_field;");
$conn->query("INSERT INTO ps_customization_field (id_product,type,required) SELECT id_product,0,0 FROM ps_product WHERE id_shop_default = 1 AND customizable = 1;");
$conn->query("INSERT INTO ps_customization_field (id_product,type,required) SELECT id_product,1,1 FROM ps_product WHERE id_shop_default = 1 AND customizable = 1;");
echo "Added uploadable files & customized field to each item!<br /><br />";
$conn->query("truncate table ps_customization_field_lang;");
$conn->query("INSERT INTO ps_customization_field_lang (id_customization_field, id_lang,id_shop,name) select id_customization_field,1,1,'Upload 1' from ps_customization_field WHERE type = 0;");
$conn->query("INSERT INTO ps_customization_field_lang (id_customization_field, id_lang,id_shop,name) select id_customization_field,1,1,'Field 1' from ps_customization_field WHERE type = 1;");
echo "Added appropriate labeling for each field, for each product!<br /><br />";
echo "<h2>Yay, We're done!</h2>";
$conn->close();
Obviously this can be updated/changed to meet the requirements of whomever.

Joomla Jdatabase query code with join does not work

I run the php code below within the 'Eval' section of a Fabrik form element. The code is supposed to return/put a number in a form field, but nothing appears in the form field.
When I used another query (refer to '$query-> ' lines) the code does work, so I get the impression that the query contains errors; however, when executing the related webpage with the form fields no sql error appears.
I have no idea what is wrong with the query(?)
Code:
$form_productname = 'testproduct';
$form_username = 'myname';
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
//$query->select($db->quoteName(array('a.id', 'b.productid')));
$query->select($db->quoteName('b.productid'));
$query->from($db->quoteName('#__products', 'b'));
$query->join('INNER', $db->quoteName('#__extendedreg_users', 'a') . ' ON (' . $db->quoteName('a.user_id') . ' = ' . $db->quoteName('b.owner') . ')
AND (' . $db->quoteName('a.cf_collectivename') . ' = ' . $db->quote($form_username) . ')
AND (' . $db->quoteName('b.productname') . ' = ' . $db->quote($form_productname)).')'.;
//echo $query;exit;
$db->setQuery($query);
$db->execute();
$results = $db->loadObjectList();
return count($results);
UPDATE: cause was syntax php error in where statement:
. $db->quote($form_productname)).
must be:
. $db->quote($form_productname).
You are not getting any errors because you are not catching any errors. Have a look at How to do SQL exception / error handling.
Do at least a $query->dump() and run your query in a console if you can't figure out what is wrong.
I don't understand why are you quoting the value you are comparing $form_username and $form_productname. But maybe it's late and I am tired.

Load data infile mysql statement in perl error handling

Below is my perl code
I referred to the following link http://www.tol.it/doc/MySQL/chapter6.html. If there is a better please post.
use Mysql;
my $db = Mysql->connect($mysqlhost, $mysqlDB, $mysqlUser, $mysqlPassword);
$db->selectdb("$mysqlDB");
my $loadQuery="LOAD DATA INFILE '$filename' INTO TABLE $pageURLTable FIELDS TERMINATED BY '\\t' LINES TERMINATED BY '\\n'";
print "Executing $loadQuery";
my $loadresult=$db->query($loadQuery);
if(!$loadresult){
print "Error: MySQl Load failed.System error message:$!.";
return -1;
}
print "Info:".$loadresult->info"; ## this raises error MySQL::Statement info not loadable;
What is wrong ?
Can you suggest a better way of coding this so that Load data file errors are better captured?
Thanks,
Neetesh
Try to use ->do method instead of ->query.
Make sure that Load Data Inline is enabled in your database.
If above don't work, you can use system(mysql -e "LOAD DATA INFILE...")
I generally use DBI recipes. "executing sql statement" I like to do something like $rows = $sth->execute(); Gives affected rows by last statement, and if rows >0 after loading csv files I'know that I've successfully loaded data in database.
my $sth = $dbh->prepare($sql)
or die "Can't prepare SQL statement: ", $dbh->errstr(), "\n";
$rows = $sth->execute();
if ($rows>0)
{
print "Loaded $rows rows\n" if ($Debug);
}
else {
print "Can't execute SQL statement: ", $sth->errstr(), "\n";
}

Searching MySQL DB using PHP

I use CodeIgniter + MySQL.
I am succeeding in running this query and parsing the result.
$var1 = $this->db->query("select title from stores where title like \"" . $str . "%\" union select title from coupons where title like \"" . $str . "%\"");
return $var1;
And in the controller, I parse the result() of this query to a JSON file using json_encode
But when I run the same query on another table, and follow the same step in parsing, I am facing parsing problems.
$var1 = $this->db->query("select tagword from tags where tagword like \"" . $str ."%\"");
Am I doing something wrong here?
Try echo-ing your SQL Statement
echo $this->db->last_query();
Then try Run SQL query/queries on your database for your debugging purpose

MySQL error in Perl ( Errorcode 2)

I am complete newbie in Perl. I have this little sub
sub processOpen{
my($filename, $mdbh)=#_;
my($qr, $query);
# parse filename to get the date extension only
# we will import the data into the table with this extension
# /home//logs/open.v7.20120710_2213.log
my(#fileparts) = split(/\./, $filename);
my(#filedateparts) = split(/_/, $fileparts[2]);
my($tableext) = $filedateparts[0];
$query = "LOAD DATA INFILE '" . $filename . "' INTO TABLE open_" . $tableext . " FIELDS TERMINATED BY '||' LINES TERMINATED BY '\n'
(open_datetime, open_date, period,tag_id)";
$qr = $$mdbh->prepare($query);
$qr->execute(); # causes error (see below)
$qr->finish();
}
And I'm getting the following error:
DBD::mysql::st execute failed: Can't get stat of '/home/logs/open..v7.20120710_2213.log' (Errcode: 2) at /home/thisfile.pm line 32.
Line 32 is the $qr->execute();
Error Code 2 is most likely "File not found".
Does your file exist? Note that if you are running the perl on a separate host from the MySQL database, the file must be on the database host, not the client host.