MySql SELECT multiple according to form input and publish

249 views Asked by At

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    
1

There are 1 answers

10
mickmackusa On BEST ANSWER

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