phpjoomla4

$db->insertid() return 0 event when no error in $db->execute()


I am developing an extension in Joomla 4.

I need to insert a record, so I did this:

        $columns = array('first_name', 'last_name', 'email', 'cellular', 'checked_out_time');
        $values = array($db->quoteName($nombre), $db->quoteName($apellido), $db->quoteName($email), $db->quoteName($celular), $db->quoteName($fecha->toSQL()));
        
        $saveQuery
                ->insert($db->quoteName('#__compra_tickets_apoderado'))
                ->columns($db->quoteName($columns))
                ->values(implode(',', $values));
        
        $db->setQuery($query);
        if (false !== ($result = $db->execute())) {
            echo $db->insertid();
        } else {
            echo 0;
        }

Even when execute method returns true, no record is inserted and $db->insertid() return 0.

Any hint, please?


Solution

  • It looks like you use $saveQuery for building the query, but then you pass $query to setQuery() which is most likely different query you crafted earlier. So that's why you do not get any warning about using unassigned variable (because it exists), and because its content is a valid query, the execute() technically works, but "this is not the query you are looking for"®. And as since that old query is non-INSERT (my guess, just SELECT so you do not mess with your data with that double query execution), there's nothing inserted to get the insertid() of.

    Side note: quoteName() is used to escape database identifiers, such as column names, not values as you did. For inserting values, you should use quote() instead.