This topic contains a post which is marked as Best Answer. Press here if you would like to see it.
*

mwindey

  • *****
  • 484 posts
Unable to insert new keyword category mapping (own add-on)
« on: April 20, 2024, 12:06:29 PM »
I wrote a script to search for keyword and catId from items that users are posting to my website and save this for later use ....I'm unable to get the correct data into the database. The data is being requested and when sent, it's correctly passed to the payload in the console. In the queries log, these entries also appear in the table mdr_item_archive, so they are being sent. However, they're not appearing in the table oc_t_keyword_category_mapping, which I created myself. I've been searching for a solution for days but I think there's a flaw in the logic...
Table DROP TABLE IF EXISTS `oc_t_keyword_category_mapping`;
CREATE TABLE `oc_t_keyword_category_mapping` (
  `id` int(11) NOT NULL,
  `keyword` varchar(255) DEFAULT NULL,
  `category` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ALTER TABLE `oc_t_keyword_category_mapping`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `oc_t_keyword_category_mapping`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Function is in modelEPS (epsilon theme) and is called by item-post on posting the listing. Untill there everything is ok but i guess the logic in the model is not correct.... This is what i have so far:
Code: [Select]
public function saveCategoryMapping($keyword, $catId) {
    try {
        $existingMapping = $this->dao->select('*')
            ->from($this->getTable_keyword_category_mapping())
            ->where('keyword', $keyword)
            ->get();

        if ($existingMapping && $existingMapping->numRows() > 0) {
            $data = array(
                'category' => $catId
            );
            $this->dao->where('keyword', $keyword);
            $this->dao->update($this->getTable_keyword_category_mapping(), $data);
        } else {
            $data = array(
                'keyword' => $keyword,
                'category' => $catId
            );
            $this->dao->insert($this->getTable_keyword_category_mapping(), $data);
        }

    } catch (Exception $e) {
        throw $e;
    }
}


Please help....

*

MB Themes

Re: Unable to insert new keyword category mapping (own add-on)
« Reply #1 on: April 20, 2024, 01:11:39 PM »
Code looks fine, try to debug what params you are entering to function.
Enable database debug log and at the end of function add exit.
After oublish you will be able to see wueries executed on DB and check i its not query issue
  To get fast support, we need following details: Detail description, URL to reproduce problem, Screenshots

*

mwindey

  • *****
  • 484 posts
Re: Unable to insert new keyword category mapping (own add-on)
« Reply #2 on: April 20, 2024, 02:08:25 PM »
In queries.log there is no table inserts on the table  ...  Table mdr_item_archive however has:  "select_1\":0,\"selectedCategoryId\":294,\"keywordMapping\":\'jas:294\",\"countryId\":\"be\",\".......... etc....
keywordmapping is what needs to be in in keyword and category colums from table keyword_category_mapping. Shouldn't this be more specific like "keywordMapping\":\"keyword: jas: category 294\",\" ?
Payload in console after posting:
octoken: llhx4gaxmimg
action: item_add_post
page: item
sKeyword: jas
foundCategory: 294
catId: 294
select_1: 0
selectedCategoryId: 294
keywordMapping: jas:294
octoken: llhx4gaxmimg

Params to model in item-post after validate (end of page):
Code: [Select]
    contactEmail: {
      required: '<?php echo osc_esc_js(__('Email: this field is required.''epsilon')); ?>',
      email: '<?php echo osc_esc_js(__('Email: invalid format of email address.''epsilon')); ?>'
    }
 },

  ignore: ":disabled",
  ignoreTitle: false,
  errorLabelContainer: "#error_list",
  wrapper: "li",
  invalidHandler: function(form, validator) {
    $('html,body').animate({ scrollTop: $('body').offset().top}, { duration: 250, easing: 'swing'});
  },
  submitHandler: function(form){
    $('button[type=submit], input[type=submit]').attr('disabled', 'disabled');
    form.submit();
  }
   });
});
// Code to save keyword and id into database
if (Params::existParam('keywordMapping')) {
    $keywordMapping = Params::getParam('keywordMapping');
    if (!empty($keywordMapping)) {
        list($keyword, $catId) = explode(':', $keywordMapping);
        ModelEPS::newInstance()->saveCategoryMapping($keyword, $catId);
    }
}
</script>
<?php osc_current_web_theme_path('footer.php'); ?>
</body>
</html>

Witch i guess is not activating the modelEPS function... Maybe this should be in functions instead of item-post after validating code....
« Last Edit: April 20, 2024, 08:36:57 PM by mwindey »

*

MB Themes

Re: Unable to insert new keyword category mapping (own add-on)
« Reply #3 on: April 21, 2024, 09:29:33 AM »
That should be activated probably on when user select category based on keyword? (Ajax)
  To get fast support, we need following details: Detail description, URL to reproduce problem, Screenshots

Marked as best answer by frosticek on April 21, 2024, 02:42:04 PM
*

mwindey

  • *****
  • 484 posts
Re: Unable to insert new keyword category mapping (own add-on)
« Reply #4 on: April 21, 2024, 02:09:31 PM »
The wonder of using hooks  :P :) I moved the item-post part to functions and changed code to:
Code: [Select]
function save_category_mapping_hook($item) {
    $keyword = isset($_POST['sKeyword']) ? $_POST['sKeyword'] : '';
    $catId = isset($_POST['catId']) ? $_POST['catId'] : '';
    ModelEPS::newInstance()->saveCategoryMapping($keyword, $catId);
}
osc_add_hook('posted_item', 'save_category_mapping_hook');

In modelEPS:
Code: [Select]
// SEARCH FOR CATEGORIES
public function findCategories($pattern, $limit = 6) {
    // Query voor zoeken in category_description
    $this->dao->select('c.pk_i_id, c.fk_i_parent_id, d.s_name, p.s_name as s_name_parent');
    $this->dao->from($this->getTable_category() . ' as c');
    $this->dao->join($this->getTable_category_description() . ' as d', '(c.pk_i_id = d.fk_i_category_id AND d.fk_c_locale_code = "' . osc_current_user_locale() . '")', 'INNER');
    $this->dao->join($this->getTable_category_description() . ' as p', '(c.fk_i_parent_id = p.fk_i_category_id AND p.fk_c_locale_code = "' . osc_current_user_locale() . '")', 'LEFT OUTER');
    $this->dao->where('c.b_enabled', 1);
    $this->dao->where(sprintf('d.s_name like "%%%s%%"', osc_esc_html($pattern)));
    $this->dao->limit($limit);
    $result1 = $this->dao->get();

    // Query voor zoeken in keyword_category_mapping
    $this->dao->select('c.pk_i_id, c.fk_i_parent_id, d.s_name, p.s_name as s_name_parent');
    $this->dao->from($this->getTable_category() . ' as c');
    $this->dao->join($this->getTable_keyword_category_mapping() . ' as kc', 'c.pk_i_id = kc.category', 'INNER');
    $this->dao->join($this->getTable_category_description() . ' as d', '(c.pk_i_id = d.fk_i_category_id AND d.fk_c_locale_code = "' . osc_current_user_locale() . '")', 'INNER');
    $this->dao->join($this->getTable_category_description() . ' as p', '(c.fk_i_parent_id = p.fk_i_category_id AND p.fk_c_locale_code = "' . osc_current_user_locale() . '")', 'LEFT OUTER');
    $this->dao->where('c.b_enabled', 1);
    $this->dao->where(sprintf('kc.keyword = "%s"', osc_esc_html($pattern)));
    $this->dao->limit($limit);
    $result2 = $this->dao->get();

    // Combineer de resultaten
    $data = array();
    if ($result1 && $result1->numRows() > 0) {
        $data = array_merge($data, $result1->result());
    }
    if ($result2 && $result2->numRows() > 0) {
        $data = array_merge($data, $result2->result());
    }

    return $data;
}


// SAVE WRONG SPELLED TO DATABASE MAPPING FOR LATER USE
public function saveCategoryMapping($keyword, $catId) {
    try {
        // Check if the category mapping already exists for the specified keyword
        $existingMapping = $this->dao->select('*')
            ->from($this->getTable_keyword_category_mapping())
            ->where('keyword', $keyword)
            ->get();

        if ($existingMapping && $existingMapping->numRows() > 0) {
            // Update the existing record if the mapping already exists
            $data = array(
                'category' => $catId
            );
            $this->dao->where('keyword', $keyword);
            $this->dao->update($this->getTable_keyword_category_mapping(), $data);
        } else {
            // Add a new record if the mapping does not exist yet
            $data = array(
                'keyword' => $keyword,
                'category' => $catId
            );
            $this->dao->insert($this->getTable_keyword_category_mapping(), $data);
        }
    } catch (Exception $e) {
        // Log the error for debugging purposes
        error_log('Error in saveCategoryMapping: ' . $e->getMessage());
        // Optionally, you can throw the exception again to propagate it further
        // throw $e;
    }
}

// USE WRONG SPELLED TO SEARCH FOR CATEGORY IN CATEGORY
public function suggest_category_ajax() {
    try {
        $keyword = Params::getParam('keyword');

        $output = array();

        // Zoek naar categorieën op basis van het trefwoord in verschillende tabellen
        $this->dao->select('kc.keyword, cd.s_name');
        $this->dao->from($this->getTable_keyword_category_mapping() . ' as kc');
        $this->dao->join($this->getTable_category_description() . ' as cd', 'kc.category = cd.fk_i_category_id', 'INNER');
       
        // Controleer op zoekwoord in verkeerd gespelde woorden of exacte overeenkomsten
        if ($keyword != '') {
            $this->dao->where(sprintf('(kc.keyword = "%s" OR kc.keyword LIKE "%%%s%%")',
                mysqli_real_escape_string($this->dao->connId, $keyword),
                mysqli_real_escape_string($this->dao->connId, $keyword)
            ));
        }

        $result = $this->dao->get();

        if ($result && $result->numRows() > 0) {
            // Categorieën gevonden, voeg ze toe aan de output
            $output['categories'] = $result->result();
        } else {
            // Als er geen overeenkomst is gevonden in oc_t_keyword_category_mapping,
            // probeer dan te zoeken in de categoriebeschrijvingstabel
            $this->dao->clear(); // Maak de vorige query ongedaan

            // Zoek naar categorieën op basis van het trefwoord in de categoriebeschrijvingstabel
            $this->dao->select('NULL as keyword, cd.s_name');
            $this->dao->from($this->getTable_category_description() . ' as cd');
            $this->dao->where(sprintf('cd.s_name LIKE "%%%s%%"', mysqli_real_escape_string($this->dao->connId, $keyword)));

            $result = $this->dao->get();

            if ($result && $result->numRows() > 0) {
                // Categorieën gevonden, voeg ze toe aan de output
                $output['categories'] = $result->result();
            } else {
                // Als er nog steeds geen overeenkomst is gevonden, geef een foutmelding
                echo json_encode(array('error' => 'No categories found for the provided keyword.'));
                exit;
            }
        }

        // Zoek naar de laatste zoekopdrachten op basis van het patroon
        $output['latest_searches'] = $this->findLatestSearches($keyword, 6);

        // Retourneer de output als JSON-gegevens
        header('Content-Type: application/json');
        echo json_encode($output);
        exit;

    } catch (Exception $e) {
        // Foutafhandeling
        echo json_encode(array('error' => $e->getMessage()));
        exit;
    }
}

Works like a charm now  8)
« Last Edit: April 22, 2024, 09:16:22 PM by mwindey »

*

MB Themes

Re: Unable to insert new keyword category mapping (own add-on)
« Reply #5 on: April 21, 2024, 02:41:58 PM »
Cool  ;)
  To get fast support, we need following details: Detail description, URL to reproduce problem, Screenshots