Passing $_GET variables.

A collection of tutorials and posts that show additional functionality of MATE

Moderator: KarelB

Passing $_GET variables.

Postby KarelB » Mon Jul 05, 2010 1:47 pm

One question that comes back regular is how to pass $_GET (or $_POST) variables to the MATE software.

This is possible and actually rather simple.
The basic idea is that the $_GET variable is glued to the URL in the displayHtml function and is then available again in the initiateEditor function as a $_GET variable.

As an example I will build a Table Monitor where the name of the table is passed as a $_GET variable. This example assumes that all of your tables in your database have a column 'id'. Also the code is for the paid version, but it works in the same way in the free version.

So first we have to adjust the displayHtml function to add a dropdown with all the table names in your database and reload the page with the table name attached to the URL:
Code: Select all

function displayHtml()
{
   $js = '<script type="text/javascript">
   <!--
   function myjumpMenu(targ,selObj,restore){ //v3.0
     eval(targ+".location=\'"+selObj.options[selObj.selectedIndex].value+"\'");
     if (restore) selObj.selectedIndex=0;
   }
   //-->
   </script>';
   echo $js;
   

   $query = 'SHOW TABLES';
   $result = mysql_query($query) or die("Could not query: ". mysql_error());
   
   $shtml = '<h1>Table monitor</h1>
           <form action="" method="get">
            <select name="jumpMenu" id="jumpMenu" onchange="myjumpMenu(\'parent\',this,0)">
           <option value="">--- Kies Tabel ---</option>';

   while ($td = mysql_fetch_array($result)) {
      $tbl = $td[0];
      $shtml .=  '<option value="'.$_SERVER["PHP_SELF"].'?tbl='.$tbl.'">'.$tbl.'</option>';
   }
   
   $shtml .= '</select></form>';   
   echo $shtml;

   $html = '
      <div id="historyContainer">
         <div id="information">
                        ......
                        ......

}

The javascript portion is to directly reload the page (jump Menu) as soon as you select the table name.

Next we need to glue the $_GET variable to the URL.
Also in the function displayHtml find the line with the URL
Code: Select all
setAjaxInfo({url: "'.$_SERVER["PHP_SELF"].'", history: true});

and replace with :
Code: Select all
setAjaxInfo({url: "'.$_SERVER["PHP_SELF"].'?tbl='.$_GET["tbl"].'", history: true});


Now the variable gets passed and it is available in the initiateEditor function as a $_GET variable again.

Since it is empty the first time the script is invoked we need a default tablename and since you are using MATE you should have a table called “mate_columns”:
Code: Select all
$dump_table = ! empty($_GET['tbl']) ? $_GET['tbl'] : 'mate_columns';


Now we can use the variable $dump_table to query for the fields of the table and build the $tableColumns array.
Code: Select all
$query = 'SHOW COLUMNS FROM '.$dump_table ;
$result = mysql_query($query) or die("Could not query: ". mysql_error());

while ($row = mysql_fetch_assoc($result)){
   $tableColumns[$row['Field']] = array('display_text' => $row['Field'], 'perms' => 'VTXQX');
}


As the last step we should set tne $tableName:
Code: Select all
$tableName = $dump_table ;


And here is the complete code of the script.
Code: Select all
<?php
require_once('../include/Common32.php');
require_once('../mate-3.2/php/lang/LangVars-nl.php');
require_once('../mate-3.2/php/AjaxTableEditor.php');
class TableMonitor extends Common
{
   
   function displayHtml()
   {
      $js = '<script type="text/javascript">
      <!--
      function myjumpMenu(targ,selObj,restore){ //v3.0
        eval(targ+".location=\'"+selObj.options[selObj.selectedIndex].value+"\'");
        if (restore) selObj.selectedIndex=0;
      }
      //-->
      </script>';
      echo $js;
      
   
      $query = 'SHOW TABLES';
      $result = mysql_query($query) or die("Could not query: ". mysql_error());
      
      $shtml = '<h1>Table monitor</h1>
                <form action="" method="get">
               <select name="jumpMenu" id="jumpMenu" onchange="myjumpMenu(\'parent\',this,0)">
              <option value="">--- Kies Tabel ---</option>';

       while ($td = mysql_fetch_array($result)) {
         $tbl = $td[0];
         $shtml .=  '<option value="'.$_SERVER["PHP_SELF"].'?tbl='.$tbl.'">'.$tbl.'</option>';
       }
      
       $shtml .= '</select></form>';   
       echo $shtml;
   
      $html = '
         <div id="historyContainer">
            <div id="information">
            </div>
      
            <div id="titleLayer" style="padding: 2px; font-weight: bold; font-size: 18px; text-align: left;">
            </div>
      
            <div id="tableLayer" align="left" style=" width: 100%; overflow-x:auto; position: relative;">
            </div>
            
            <div id="recordLayer" align="left" style="width:900px">
            </div>      
            
            <div id="searchButtonsLayer" align="left">
            </div>
         </div>
         
         <br /><br /><br />';
      echo $html;
      
      // Set default session configuration variables here
      $defaultSessionData['orderByColumn'] = 'id';
      
      
      $defaultSessionData = base64_encode($this->Editor->jsonEncode($defaultSessionData));
      
      
      $javascript = '   
         <script type="text/javascript">
            setAjaxInfo({url: "'.$_SERVER["PHP_SELF"].'?tbl='.$_GET["tbl"].'", history: true});
            if(ajaxInfo.history == false)
            {
               toAjaxTableEditor("update_html","");
            }
            else if(window.location.hash.length == 0)
            {
               var defaultInfo = {info: "", action: "update_html", sessionData: "'.$defaultSessionData.'"};
               window.location.href = window.location.href+"#"+Base64.encode(Object.toJSON(defaultInfo));
            }
         </script>';
      echo $javascript;
   }   
   
   
   function initiateEditor()
   {
        $dump_table = ! empty($_GET['tbl']) ? $_GET['tbl'] : 'mate_columns';
      
      $query = 'SHOW COLUMNS FROM '.$dump_table ;
      $result = mysql_query($query) or die("Could not query: ". mysql_error());

       while ($row = mysql_fetch_assoc($result)){
         $tableColumns[$row['Field']] = array('display_text' => $row['Field'], 'perms' => 'VTXQX');
       }
       
      $tableName = $dump_table ;
      $primaryCol = 'id';
      $errorFun = array(&$this,'logError');
      
      $permissions = 'VIQSX';
      
      require_once('../mate-3.2/php/AjaxTableEditor.php');
      $this->Editor = new AjaxTableEditor($tableName,$primaryCol,$errorFun,$permissions,$tableColumns);
      $this->Editor->setConfig('tableInfo','cellpadding="1" width="100%" class="mateTable"');
      $this->Editor->setConfig('tableTitle',$dump_table);
      $this->Editor->setConfig('paginationLinks',true);   
      $this->Editor->setConfig('iconColPosition','first');
       }

   function __construct()
   {
      session_start();
      $this->mysqlConnect();
      $this->initiateEditor();
      if(isset($_POST['json']))
      {
         if(ini_get('magic_quotes_gpc'))
         {
            $_POST['json'] = stripslashes($_POST['json']);
         }
         $this->Editor->data = $this->Editor->jsonDecode($_POST['json']);
         $this->Editor->setDefaults();
         $this->Editor->main();
         echo $this->Editor->jsonEncode($this->Editor->retArr);
      }
      else if(isset($_GET['export']))
      {
         $this->Editor->data->sessionData = $_GET['session_data'];
         $this->Editor->setDefaults();
         //echo mb_convert_encoding($this->Editor->exportInfo(),"Windows-1252","UTF-8");
         echo $this->Editor->exportInfo();
         header('Cache-Control: no-cache, must-revalidate');
         header('Pragma: no-cache');
         header('Content-type: application/x-msexcel');
         header('Content-Type: text/csv');
         header('Content-Disposition: attachment; filename="'.$this->Editor->tableName.'.csv"');
         exit();
      }
      else if(isset($_POST) && count($_POST) > 0)
      {
         $this->Editor->setDefaults();
         $this->Editor->handleFileUpload();
        }
      else
      {
         $this->displayHeaderHtml();
         $this->displayHtml();
         $this->displayFooterHtml();
      }
   }

}
$lte = new TableMonitor();
?>

Now you should have a very simple Table Monitor where the tablename is passed as a $_GET variable.
That is all.
KarelB
 
Posts: 429
Joined: Mon Dec 01, 2008 11:49 pm
Location: The Netherlands

Re: Passing $_GET variables.

Postby jcskyrock » Tue Aug 10, 2010 8:32 pm

I found this quite hard to follow. Should I be building a whole new file, or can I add this code to an existing PHP file. Like, for example, JoinExample.php?
jcskyrock
 
Posts: 12
Joined: Tue Aug 10, 2010 1:55 pm

Re: Passing $_GET variables.

Postby admin » Fri Sep 10, 2010 1:42 pm

Here is some php code that will take $_GET variables and automatically append them to the $ajaxUrl. Just run this php code to create the ajax url and then you will have access to $_GET variables during ajax requests.

Code: Select all
      $ajaxUrl = $_SERVER['PHP_SELF'];
      if(count($_GET) > 0)
      {
         $queryStrArr = array();
         foreach($_GET as $var => $val)
         {
            $queryStrArr[] = $var.'='.urlencode($val);
         }
         $ajaxUrl .= '?'.implode('&',$queryStrArr);
      }
admin
Site Admin
 
Posts: 1433
Joined: Fri Jul 11, 2008 1:34 am

Re: Passing $_GET variables.

Postby KarelB » Wed Sep 15, 2010 5:59 pm

@jcskyrock,

Sorry for the late reply, I have been on holidays.
The example given here is a complete script. The last codebox contains the complete code for a new script and should run correctly once you have installed MATE successfully.
It is just an example to demonstrate how to pass $_GET variables. The same technique can be used in any existing script you have.
In addition if you use the clever code admin posted you won't have to bother about the correct syntax in the url.
KarelB
 
Posts: 429
Joined: Mon Dec 01, 2008 11:49 pm
Location: The Netherlands

Re: Passing $_GET variables.

Postby lexo » Wed Oct 13, 2010 11:10 am

Hi, im new in php's stuff, i tested the scrip above and run fine returning >> "/name.php?Description=B707" an url as you said, but i don't know how extract only B707 to be used below.. i

Code: Select all
$Description=$_GET["Description"];
$this->Editor->setConfig('sqlFilters', "Description = '".$Description."'");


i try this,

Code: Select all
//your script here

$this->Editor->setConfig('sqlFilters', "Description = ' ".$ajaxUrl." ' ");


but dsn't work!!

also change to this
Code: Select all
$this->Editor->setConfig('sqlFilters', "Description = '.$ajaxUrl.' ");


amd the same, what i'a doing wrong?
lexo
 
Posts: 15
Joined: Sat Oct 09, 2010 1:35 pm

Re: Passing $_GET variables.

Postby lexo » Wed Oct 13, 2010 11:39 am

Hi again, i change a bit your script to only obtain B707 and not the entire URL, ....

Code: Select all
if(count($_GET) > 0)
          {
             $queryStrArr = array();
             foreach($_GET as $var => $val)
             {
                $queryStrArr[] = $val;
             }
             $ajaxUrl = implode('&',$queryStrArr);
          }

$this->Editor->setConfig('sqlFilters', "Description = '.$ajaxUrl.'");


but in $this->...... still don't work, and the problems is how put correctly $ajaxUrl inside ->setConfig('sqlFilter', "......");

Help me please!! :cry:
lexo
 
Posts: 15
Joined: Sat Oct 09, 2010 1:35 pm

Re: Passing $_GET variables.

Postby KarelB » Thu Oct 14, 2010 7:12 pm

Did you actually try your first suggestion:
Code: Select all
$Description=$_GET["Description"];
$this->Editor->setConfig('sqlFilters', "Description = '".$Description."'");

as this should be the correct way to use the $_GET variables. What errors did you get?

Another way to debug what is happening is using the viewQuery config option:
Code: Select all
$this->Editor->setConfig('viewQuery', true);

This will output the SQL that is generated by MATE.
KarelB
 
Posts: 429
Joined: Mon Dec 01, 2008 11:49 pm
Location: The Netherlands

Re: Passing $_GET variables.

Postby lexo » Thu Oct 14, 2010 9:19 pm

yes i used that way too!!
select `parts`.`partnumber`,
`parts`.`nomenclature`,
`parts`.`manufacturer`,
Description as `i_c_code`,
`parts`.`manual`
from parts
left join `aircrafts` as `aircrafts_84413_0` on `parts`.`i_c_code` = `aircrafts_84413_0`.`Description`
where Description = ''
order by `i_c_code` asc limit 0, 15

with both ways...

Code: Select all
$Description=$_GET["Description"];
$this->Editor->setConfig('sqlFilters', "Description = ' ".$Description." ' ");           


Code: Select all
$this->Editor->setConfig('sqlFilters', "Description = '".$_GET["Description"]."'");


its seem like $_GET not recieve data inside the funtion initiateEditor()... becouse inside the funtion displayHtml() works fine
Code: Select all
$Description=$_GET["Description"]; echo $Description;
but there i can not use
Code: Select all
$this->Editor->setConfig('sqlFilters', "Description = '".$_GET["Description"]."'");
becouse give me errors.
lexo
 
Posts: 15
Joined: Sat Oct 09, 2010 1:35 pm

Re: Passing $_GET variables.

Postby KarelB » Thu Oct 14, 2010 9:27 pm

Please post your entire source code so we can see what might be the issue.
KarelB
 
Posts: 429
Joined: Mon Dec 01, 2008 11:49 pm
Location: The Netherlands

Re: Passing $_GET variables.

Postby lexo » Thu Oct 14, 2010 9:52 pm

Code: Select all
<?php
require_once('Common.php');
require_once('php/lang/LangVars-en.php');
require_once('php/AjaxTableEditor.php');
session_start();

class Search extends Common
{
    var $Editor;
    var $filtro;
   
    function displayHtml()
    {
   
    ?>
               
<html>
<head>
<title>General MRO Aerospace :: Repair &amp; Overhaul  ::  Capabilities Search</title>
<style type="text/css">
div#container
{
   width: 960px;
   position: relative;
   margin-top: 0px;
   margin-left: auto;
   margin-right: auto;
   text-align: left;
}
</style>
<style type="text/css">
body
{
   text-align: center;
   margin: 0;
   background-color: #5A5A5A;
   color: #000000;
}
</style><link rel="stylesheet" type="text/css" href="./css/menutop.css">
</head>
<body>
<div id="container">

<div id="wb_Image2" style="position:absolute; left:1px; top:231px; width:957px; height:465px; z-index:0;" align="left">
<img src="images/mitte_02.jpg" id="Image2" alt="" align="top" border="0" style="width:957px;height:460px;"></div>
<div id="wb_Image6" style="position:absolute; left:343px; top:236px; width:28px; height:26px; z-index:2;" align="left">
<img src="images/flor.png" alt="" name="Image6" border="0" align="top" id="Image6" style="width:28px;height:26px;"></div>
<div id="wb_Text10" style="position:absolute; left:387px; top:241px; width:482px; height:18px; background-color:#C0C0C0; z-index:3;" align="left">
<font style="font-size:15px" color="#00008B" face="Arial"><b>REPAIR &amp; OVERHAUL | Capabilities Search</b></font></div>
<div id="wb_Image1" style="position:absolute;left:0px;top:0px;width:960px;height:200px;z-index:6;" align="left">
<img src="images/Banner5.png" id="Image1" alt="" align="top" border="0" style="width:960px;height:200px;"></div>
<div id="wb_Image4" style="position:absolute; left:1px; top:691px; width:957px; height:110px; z-index:7;" align="left">
<img src="images/unten_banner_01.jpg" id="Image4" alt="" align="top" border="0" style="width:957px;height:110px;"></div>
<div id="wb_Text2" style="position:absolute; left:3px; top:720px; width:952px; height:30px; z-index:8;" align="center">
<?php include('./css/footer.php'); ?>
</div>
<div id="wb_Image5" style="position:absolute;left:1px;top:197px;width:957px;height:37px;z-index:9;" align="left">
<img src="images/mittea.jpg" id="Image5" alt="" align="top" border="0" style="width:957px;height:37px;"></div>
<div id="wb_NavigationBar2" style="position:absolute;left:25px;top:235px;width:222px;height:181px;z-index:10;" align="left">
<?php
//Carga en la variable $texto todo el contenido de menuside.html que es menu lateral
$textoa = file_get_contents("./css/menuside.html");
//Escribe el contenido de $texto en el Codigo HTML de tu web
echo $textoa;
?>
</div>
<div id="wb_Text3" style="position:absolute; left:275px; top:268px; width:659px; height:435px; overflow:auto; z-index:11;" align="center">

<?     
        $Description=$_GET["Description"];
        $trimmed=trim($Description);
        echo "The aircraft typed was: ".$Description;
        if($trimmed== "") {
         echo "<p class=\"errorbox\">Please type an Aircraft to look for!<br><br>&nbsp;&nbsp;&nbsp; <a href=\"ro_capasearch.php\">type it.</a></p>";   
         exit;
        } ?>
       
<font style="font-size:13px" color="#000000" face="Arial"></font>
<div align="left" style="position: relative;"><div id="ajaxLoader1"><font color="#000000" face="Arial" style="font-size:13px">
  </font>
    <div align="center"><font color="#000000" face="Arial" style="font-size:13px">
      <div align="left"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/ajax_loader.gif" alt="Loading..." /></div>
    </font></div>
</div>
</div>
<font style="font-size:13px" color="#000000" face="Arial">
            <div id="historyButtonsLayer" align="left">            </div>
            <div id="historyContainer">
                <div id="information">                </div>
       
                <div id="titleLayer" >                </div>
       
                <div id="tableLayer" align="center">                </div>
               
                <div id="recordLayer" align="center">                </div>       
               
                <div id="searchButtonsLayer" align="center">                </div>
            </div>
            <script type="text/javascript">
                trackHistory = false;
                var ajaxUrl = '<?php echo $_SERVER['PHP_SELF']; ?>';
                toAjaxTableEditor('update_html','');
            </script>
       
    </td>
    </tr>
</font></div>
<div id="Html1" style="position:absolute;left:160px;top:167px;width:668px;height:22px;z-index:13">
<?php include('./css/menutop.php'); ?>
</div>
</div>
   
    <?php       
           
    }

    function initiateEditor()
    {
        $tableColumns['partnumber'] = array('display_text' => 'Parts numbers', 'perms' => 'EVCTAXQSHO');
        $tableColumns['nomenclature'] = array('display_text' => 'Nomenclature', 'perms' => 'EVCTAXQSHO');
        $tableColumns['manufacturer'] = array('display_text' => 'Manufacturer', 'perms' => 'EVCTAXQSHO');
        $tableColumns['i_c_code'] = array('display_text' => 'Aircrafts', 'perms' => 'AEVTQHS', 'join' => array( 'table' => 'aircrafts', 'column' => 'Description','type' => 'left'),'req' => true, 'select_query' => "select i_c_code, Description from aircrafts");
        $tableColumns['manual'] = array('display_text' => 'Manual', 'perms' => 'EVCTAXQSHO');
        //$tableColumns['files'] = array('display_text' => 'Files', 'perms' => 'EVCTAXQSHO');
           
        $tableName = 'parts';
        $primaryCol = 'partnumber';
        $errorFun = array(&$this,'logError');
       
        session_start();
       
        switch($_SESSION["utype"])
      {
      case "1" :
        $permissions = 'EAVIDQCSXHO';
        break;
      case "2" :
        $permissions = 'EAVIDQCSXHO';
        break;
      case "3" :
        $permissions = 'EVIQS';
        break;
      case "4" :
        $permissions = 'VIQS';
        break;
      default :
        $permissions = 'Q';
        break;
      }       
       
        $this->Editor = new AjaxTableEditor($tableName,$primaryCol,$errorFun,$permissions,$tableColumns);
        $this->filtro=$_GET["Description"];
        $this->Editor->setConfig('viewQuery', true);
       
        $Description=$_GET["Description"];
        $this->Editor->setConfig('sqlFilters', "Description = '".$Description."'");           
       
        //$this->Editor->setConfig('sqlFilters', "Description = '".$_GET["Description"]."'");
       
        $this->Editor->setConfig('tableInfo','cellpadding="1" width="100%" class="mateTable"');
        $this->Editor->setConfig('orderByColumn','i_c_code');               
        $this->Editor->setConfig('addRowTitle','Add data');
        $this->Editor->setConfig('editRowTitle','Edit data');
        $this->Editor->setConfig('iconTitle','Edit data');
       
        //$Description=$_GET["Description"];
        //$this->Editor->setConfig('sqlFilters', "Description = '.$Description.'");
        //$this->Editor->setConfig('sqlFilters', "Description like '%{$_GET['Description']}%'"); Muestra los similares
    }
   
   
    function Search()
    {
        if(isset($_POST['json']))
        {
            session_start();
            // Initiating lang vars here is only necessary for the logError, and mysqlConnect functions in Common.php.
            // If you are not using Common.php or you are using your own functions you can remove the following line of code.
            $this->langVars = new LangVars();
            $this->mysqlConnect();
            if(ini_get('magic_quotes_gpc'))
            {
                $_POST['json'] = stripslashes($_POST['json']);
            }
            if(function_exists('json_decode'))
            {
                $data = json_decode($_POST['json']);
            }
            else
            {
                require_once('php/JSON.php');
                $js = new Services_JSON();
                $data = $js->decode($_POST['json']);
            }
            if(empty($data->info) && strlen(trim($data->info)) == 0)
            {
                $data->info = '';
            }
            $this->initiateEditor();
            $this->Editor->main($data->action,$data->info);
            if(function_exists('json_encode'))
            {
                echo json_encode($this->Editor->retArr);
            }
            else
            {
                echo $js->encode($this->Editor->retArr);
            }
        }
        else if(isset($_GET['export']))
        {
            session_start();
            ob_start();
            $this->mysqlConnect();
            $this->initiateEditor();
            echo $this->Editor->exportInfo();
            header("Cache-Control: no-cache, must-revalidate");
            header("Pragma: no-cache");
            header("Content-type: application/x-msexcel");
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="'.$this->Editor->tableName.'.csv"');
            exit();
        }
        else
        {
                             
            $this->displayHeaderHtml();
            $this->displayHtml();
            $this->displayFooterHtml();   
       
        }
    }
}
$lte = new Search();
?>
lexo
 
Posts: 15
Joined: Sat Oct 09, 2010 1:35 pm

Next

Return to How To

Who is online

Users browsing this forum: No registered users and 1 guest

cron