Can sql() be used inside onXXXX event of Editor? If so, how?

Can sql() be used inside onXXXX event of Editor? If so, how?

mokozukimokozuki Posts: 13Questions: 3Answers: 0

I can't find any good examples on how I can use sql() to run an arbitrary query inside of Editor's onCreate, onRemove, etc. Some questions in the forum haev some code, but seems incomplete. Any help on this would be appreciated, this should be the last piece of the puzzle to get things the way I need them to be.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin
    Answer ✓

    Hi,

    The key will be to make use of the use statement in the anonymous function for the event handler, so you have access to the $db variable (its really odd if you are coming from Javascript, but that's the way PHP does variables...).

    ->on( 'postCreate', function ( $editor, $id, $values, $row ) use ( $db ) {
      $db->sql( ... );
    } )
    

    Allan

  • mokozukimokozuki Posts: 13Questions: 3Answers: 0

    Thanks. that did the trick. I initially wanted to run two commands in one query (SELECT @p:=0; UPDATE.....) but that didn't take. so i split it up into two queries. Below query runs after adding or deleting rows (editing is not allowed, reordering is), to make sure item_order is correct and doesn't skip a number or has a duplicate number.

    .......
        ->on( 'postRemove postCreate', function() use ($db) {
        $q = 'SELECT @p:=0';
        $q2 = 'UPDATE mz_product_list_items_bak
            SET item_order=(@p:=@p+1) 
            WHERE product_list_id='.$_GET['list_id'].' 
            ORDER BY item_order ASC, last_update ASC';
        $db->sql($q);
        $db->sql($q2);
        } )
        ->process( $_POST )
        ->json();
    
This discussion has been closed.