Reputation: 2612
I'm trying to execute a query in my cron job of drupal7. However something strange is happening. Every time it tries to execute I get an PDOException. When I paste the query in phpmyadmin there is no problem and the query executes. But iin my cronjob it gives the error. The problem is not in my cronjob, I know this because it also executes other queries without any problems.
The php code of the query:
$sql_insert_product = 'INSERT INTO tblProducten(productnummer, merk, doelgroep, RefLev)'
. 'VALUES(' . $prod->productnummer . ', "tt", "' . $prod->doelgroep . '", "'
. $prod->reflev . '")';
$db_catalogus->query($sql_insert_product);
The resulted query the code produces which works in phpmyadmin:
INSERT INTO tblProducten(productnummer, merk, doelgroep, RefLev) VALUES(16657, "tt", "Meisjes", "11803")
The Exception:
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tt' in 'field list': INSERT INTO tblProducten(productnummer, merk, doelgroep, RefLev) VALUES(16657, "tt", "Meisjes", "11803"); Array ( ) in cronner_cron() (line 94 of /home/...
Upvotes: 0
Views: 467
Reputation: 157892
the problem is indeed in your query. There is a setting in mysl which makes double quote a field delimiter, instead of default apostrophe.
So, change your double quotes with single one (and modify the syntax accordingly)
$sql = "INSERT INTO tblProducten(productnummer, merk, doelgroep, RefLev)
VALUES ({$prod->productnummer}, 'tt', '{$prod->doelgroep}','{$prod->reflev}')";
$db_catalogus->query($sql);
and, to let you know, your formatting is almost unreadable, with all that unnecessary concatenations and quotes.
if you have problems with quotes, than you don't escape your values
it will lead you to SQL injection.
ALWAYS escape any string you are placing in the query.
and format other values accordingly.
add this code before your query
$prod->productnummer = intval($prod->productnummer);
$prod->doelgroep = mysql_real_escape_string($prod->doelgroep);
$prod->reflev = mysql_real_escape_string($prod->reflev);
and there won't be any problem with any quotes ever.
Upvotes: 3
Reputation: 272116
Apparently, PHPMyAdmin and your cron script run in different SQL modes. Here is an illustration of the problem:
SET sql_mode = 'ANSI_QUOTES'; # treats double quotes as an identifier quote character
SELECT "name" FROM table1;
name
=====
alpha
beta
gamma
SET sql_mode = ''; # treats double quotes as string literal quote character
SELECT "name" FROM table1;
name
=====
name
name
name
Ideally you should not use "
as string delimiter ("tt"
in your example), use single quotes instead which is a standard every SQL database will understand. Or you can play around with ANSI_QUOTES setting which I would not recommend.
Upvotes: 3