Editor event strange behaviour...
Editor event strange behaviour...
borconi
Posts: 56Questions: 19Answers: 1
Hi.
I have the following global variable:
$db2 = new PDO('mysql:host=localhost;dbname=XXXXX;charset=utf8', 'username', 'password');
I'm trying to do some work on a 'preEdit' and 'postEdit' on other tables re-using some of the edited data, but I'm having difficulties, eher is a concrete example:
->on( 'postEdit', function ( $editor, $id, $values, $row ) {
global $db2;
$nRows = $db2->query('select count(*) from `discount` where `eventid`=$id')->fetchColumn();
die($nRows);
})
I will expect the script to only print a number, but instead it returns:
<b>Fatal error</b>: Uncaught Error: Call to a member function fetchColumn() on boolean in /var/www/mybibnumber.co.uk/cms/events_data.php:139
Running, the following outside of the event, works correctly:
$nRows = $db2->query('select count(*) from `discount` where `eventid`=1')->fetchColumn(); //used 1 just for example here!
die($nRows);
Any suggestion?
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
You have to use:
That's how anonymous functions access scoped variables in PHP.
Allan
Thanks Allan.
I have the same result even with using
use
Also I admit
use
is the healthy way of doing it, based on: this it should work withglobal
as well.Also the funny thing is that other queries are executed correctly, for example:
The update executes correctly, the only one where I'm having trouble is the one where I'm trying to count the rows.
Ok, even more interesting is that if the count() returns 0 or 1 it doesn't work however if the count() returns more than 1 it works fine.
For some reason it looks like it's doing an eval on the query and because the result is 0 or 1 it treats it as a boolean, but this doesn't happen outside the event function.
I have now worked around this by actually fetching the whole content of the query to an array and counting the elements in the array, luckily this are small queries, so I don't need to fetch huge amount of data into a variable,
Good to hear you have a workaround for now.
I don't really understand why the code shown above wouldn't be working to be honest. You aren't using the Editor APIs there, and the fact that it is in an event handler function shouldn't make any difference.
The only thing I can think of is that the problem is being caused by the fact that Editor uses a transaction (which you can disable with
->transaction( false )
before the->process()
method call) and since you are using a different database context, it is tripping up.Allan
Thanks, I will check that, indeed it's an interesting one... but hey-ho I think that's why we love IT.... challenges all the time