1

I need to complete mysql_query SELECT multiple options and publish results on webpage. The form (Breezingforms) pulls data.

Joomla module to appear on webpage

<div id="frmSrchResults"></div>

"Search" button on the form with user choices to pull data from db

    function ff_Searchbutton_action(element, action)
{
    switch (action) {
        case 'click':
let var1 = ff_getElementByName('category').value;
let var2 = ff_getElementByName('subcategory').value;
let var3 = ff_getElementByName('CselCountry').value;

// call the .post
jQuery.ajaxSetup({async:false});
jQuery.post(
  '<?php return JUri::root(true); ?>/index.php', {
    option: 'com_breezingforms',
    ff_form: ff_processor.form,
    format: 'html',
    category: var1,
    subcategory: var2,
    country: var3
},
//  success: function(data) {
  function(data) {
    jQuery('#frmSrchResults').html(data);

);
            break;
        default:;
    } // switch
} // ff_Searchbutton_action

In Form Pieces-Before Form

$this->execPieceByName('ff_InitLib');

// fetch .post() parameters
$var1 = JRequest::getVar('par1');
$var2 = JRequest::getVar('par2');

if ($var1 && $var2 && $var1 !== '' && $var2 !== '') {
  $db = JFactory::getDBO();
  $db->setQuery("Query I need to complete");
  $result = $db->loadAssocList();

// clean output buffer
  while (@ob_get_level() > 0) { @ob_end_clean(); }

  echo $result;
  exit;
}

This is an example of the database structure

id  title            name           value
4   Company Name     companyname    Microsoft
4   Company Address  companyaddress someaddress
4   Country          country        USA
4   Category         category       Computer
4   Sub-category     subcategory    Software
5   Company Name     companyname    Apple
5   Company Address  companyaddress someaddress2
5   Country          country        CANADA
5   Category         category       Business
5   Sub-category     subcategory    Executive
6   Company Name     companyname    Ollivetti
6   Company Address  companyaddress someaddress3
6   Country          country        CANADA
6   Category         category       Business
6   Sub-category     subcategory    Executive

e.g. User input in the form:

Category=Business
Sub-category=Executive
Country=CANADA

Now I need to: SELECT value (according to user choice on the form. Each form element is a select list) FROM table etc. So in my example the result is expected to be something like this:

Company Name        Company Address 
Apple               someaddress2    
Ollivetti           someaddress3    
GalanopD
  • 65
  • 7
  • If a user can input `Business`, `Executive`, and `CANADA` why are you only passing `category` and `subcategory` to your ajax process? – mickmackusa Feb 09 '19 at 05:38
  • For future Joomla-related questions, please post in Joomla Stack Exchange (for many reasons). 1. It keeps that community active. 2.You are likely to receive additional best practices advice which non-Joomla users will not be able to offer. – mickmackusa Feb 09 '19 at 06:45
  • Thank you @mickmackusa. You are correct, I should have included Country too. – GalanopD Feb 09 '19 at 14:47
  • @mickmackusa I must have missed it somewhere. You are correct, it should have been under Joomla! – GalanopD Feb 09 '19 at 14:48

1 Answers1

1

I am going to assume that you are running an outdated version of Joomla because JRequest has been deprecated as of Joomla 3.x & Joomla 3.3 deprecated function for JRequest::getVar() So you should make a point off upgrading asap.

Modern syntax:

$jinput = JFactory::getApplication()->input;
$category = $jinput->get->post('par1', '', 'WORD');
$subcategory = $jinput->get->post('par2', '', 'WORD');
$country = $jinput->get->post('par3', '', 'WORD');

Then you can write your conditional like this:

if ($category && $subcategory && $country) {

Your query is going to need to group associated rows using a "pivot"; here is a solution that I posted on Joomla Stack Exchange that implements a pivot.

SQL searching for Business and Executive: (db-fiddle demo)

SELECT 
    MAX(CASE WHEN `name` = 'companyname' THEN `value` ELSE NULL END) AS `Company Name`,
    MAX(CASE WHEN `name` = 'companyaddress' THEN `value` ELSE NULL END) AS `Company Address`
FROM `ucm`
GROUP BY `id`
HAVING
    MAX(CASE WHEN `name` = 'category' THEN `value` ELSE NULL END) = 'Business'
    AND MAX(CASE WHEN `name` = 'subcategory' THEN `value` ELSE NULL END) = 'Executive'
    AND MAX(CASE WHEN `name` = 'country' THEN `value` ELSE NULL END) = 'CANADA'
ORDER BY `Company Name`;

Converting this raw SQL to Joomla-method syntax with your input variables, it can look like this:

$db = JFactory::getDbo();
$query = $db->getQuery(true)
    ->select([
        "MAX("
        . "CASE WHEN name = " . $db->q("companyname")
        . " THEN value ELSE NULL END"
        . ") AS " . $db->qn("Company Name"),
        "MAX("
        . "CASE WHEN name = " . $db->q("companyaddress")
        . " THEN value ELSE NULL END"
        . ") AS " . $db->qn("Company Address")
    ])
    ->from($db->qn("#__your_ucm_table"))
    ->group("id")
    ->having([
        "MAX("
        . "CASE WHEN name = " . $db->q("category")
        . " THEN value ELSE NULL END"
        . ") = " . $db->q($category),
        "MAX("
        . "CASE WHEN name = " . $db->q("subcategory")
        . " THEN value ELSE NULL END"
        . ") = " . $db->q($subcategory),
        "MAX("
        . "CASE WHEN name = " . $db->q("country")
        . " THEN value ELSE NULL END"
        . ") = " . $db->q($country)
    ])
    ->order($db->qn("Company Name"));

try
{
    $db->setQuery($query);
    if (!$results = $db->loadAssocList())
    {
        echo "No matches found";
    }
    else
    {
        echo "<table>";
            echo "<tr><th>", implode("</th><th>", array_keys($results[0])), "</th></tr>";
            foreach ($results as $row)
            {
                echo "<tr><td>", implode("</td><td>", $row), "</td></tr>";
            }
        echo "</table>";
    }
}
catch (Exception $e)
{
    JFactory::getApplication()->enqueueMessage("<div>Query Syntax Error, ask dev to run diagnostics</div>", 'error');
    // Don't show the following details to the public:
    //echo $query->dump();
    //echo $e->getMessage();
}

p.s. Keep in mind that you cannot simply echo your loadAssocList data.


As for your jquery, I believe you are missing the success block to the call.

success: function (data) {
    jQuery('#frmSrchResults').html(data);
},
error: function (xhr, status) {
    console.log("Bonk! Time to debug.");
}

Here is some context: https://stackoverflow.com/a/20008285/2943403

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • I tried it and it doesn't work for some reason. One think I noticed after following articles like [Try/catch syntax](https://stackoverflow.com/questions/47134924/try-catch-syntax) is that the Try/Catch does not exist in MySQL?. Could this be the reason why it is not working? – GalanopD Feb 09 '19 at 17:48
  • I tested my querying snippet on my local host to be successful before posting. If something is not working, then you will need to run diagnostics to determine the earliest point of failure. Start echoing out values that you expect to see. If `$category` and `$subcategory` do not deliver what you key into the form, then you have a html/javascript problem. If you are testing your code, you can uncomment the `getMessage()` line to see the mysql error. If you want to check the query, write ` dump()` before the `try` block and test the rendered query at your phpMyAdmin. – mickmackusa Feb 09 '19 at 21:48
  • You DID change the name of the table in my query, right? Surely, `->from($db->qn("#__your_ucm_table"))` will not work for you unless you have a table called `lmnop_your_ucm_table`. – mickmackusa Feb 09 '19 at 21:51
  • Thanks @mickmackusa your help is highly appreciated! – GalanopD Feb 09 '19 at 21:55
  • Yes I did change the table name. Thanks – GalanopD Feb 09 '19 at 21:57
  • After all I think the problem is in the actionscript of the button. Any ideas would help... – GalanopD Feb 13 '19 at 07:22
  • I have added more to the end of my answer. Please remove your posted answer -- it is not an answer. – mickmackusa Feb 17 '19 at 05:14
  • Thank you for helping me to work this out and also adding the 3rd parameter. Actually the "success" although correct, in my case didn't work but created an issue to the dependency between other elements (Region, Country). So I commented it out. The thing is that I do see the module working on my page when I click the button BUT it actually reproduces my own home page (ajax within the module) rather than showing the results of the database. Maybe I need a .php file in the root dir or something else missing to produce the results? – GalanopD Feb 21 '19 at 09:35
  • Apologies for re-posting the code as an answer but I couldn't find another way doing it. After your comment that it doesn't work as a forum, I realized how it goes. Thanks for mentioning. – GalanopD Feb 21 '19 at 09:38
  • I think I need some html ot innerHTML code inside ` function (data) { jQuery('#frmSrchResults').html(data);` in order to make it read the $results – GalanopD Feb 25 '19 at 17:51