We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 32645
    • 377 Posts
    I got loopDBChunk to work now!

    This means I can use it in my custom search form!

    I’ve noticed that the pagination comes from CodeIgniter too... which is ironic, considering that’s what I was using to create my application before I came back to MODX.

    Thanks again for this snippet, it’s saved me a lot of headaches!
      • 1373
      • 12 Posts
      Glad to hear it helped you.

      Just to clarify things:

      this file (transformFuncs.php) was ommited by mistake from the last release.
      I have added it now.

      Basically its an empty php file, unless you need custom functions in order to transform database values. Please check the documentation in readme.txt for details.

      Amir
        • 32645
        • 377 Posts
        Questions.

        1) How do you output the number of rows returned? (IE: X records found)
        2) The header and footer parameters are just text, but what happens if I want to use a chunk?

        Let’s say I have a cars table, with over 100 cars, I want my loopDBChunk to display the ID, make, model in a table presentable to the user. 

        I want to output it like this;

        <table>
        <thead>
        <tr>
        <th>ID</th><th>Make</th><th>Model</th>
        </td>
        </thead>
        <tbody>
        
        <!-- this is where the loopDBChunk outputs each row -->
        <tr>
        <td>[+ID+]</td><td>[+make+]</td>[+model+]</td>
        </tr>
        
        </tbody>
        </table>
        


        3) Where does the actual paginator (First|1|2|3|Last) get displayed?

        4) When there are no results, nothing is shown -- not even "No records found" is displayed. In my problem I require a visual statement to be produced to the user, regardless of whether there are, or aren’t any results. How do I resolve this?

        Thanks
          • 18913
          • 654 Posts
          Not sure if I should start a new topic on this, but here goes ...

          I’m trying to get loopDbChunk to replace what is now a snippet with a mix of HTML output and mysql calls. Since I would like to paginate the results of the SQL calls, loopDbChunk looks like what I need.

          The call I am trying to get to work is this :
          [!loopDbChunk? &chunkName=`displayEvents` &sql=`SELECT * FROM events WHERE 
          (year >= $current_year AND month > $current_month) 
          OR (year >= $current_year AND month = $current_month AND day >= $current_day) 
          OR (year_end >= $current_year AND month_end = $current_month AND day_end >= $current_day) 
          OR (year > $current_year) 
          OR (year_show >= $current_year AND month_show > $current_month)
          OR (year_show >= $current_year AND month_show = $current_month AND day_show >= $current_day) 
          OR (year_show > $current_year) 
          ORDER BY year, month, day LIMIT 0, *` &perPage=`4` &orderby=`id` &missingValTxt=`--`!]


          As you can tell, the SQL call varies depending upon the day it is issued. But it looks to me like loopDbChunk needs to be called from a document, so I don’t have the $current_year, $current_day, etc. variables available like I do in the PHP call.

          Can someone give me a few pointers as to how to implement loopDbChunk in a case like this? Am I correct that a snippet can’t call another snippet (because that didn’t seem to work, unless I did something really boneheaded...)

          Thanks in advance,
          Matt
            • 18913
            • 654 Posts
            Replying to myself : RTFM, specifically the part on "runSnippet".

            My bad - sorry for the bandwidth waste....
            Matt
              • 18913
              • 654 Posts
              I tweaked LoopDBChunk to work with an external database and thought I would share the steps.

              In a document I call a snippet entitled EventLister
                [!EventLister!]
              

              which contains the following code :
              <?php
              include("assets/snippets/eventlister/config.php");
              
              $query="SELECT * FROM events WHERE 
              (year >= $current_year AND month > $current_month) 
              OR (year >= $current_year AND month = $current_month AND day >= $current_day) 
              OR (year_end >= $current_year AND month_end = $current_month AND day_end >= $current_day) 
              OR (year > $current_year) 
              OR (year_show >= $current_year AND month_show > $current_month)
              OR (year_show >= $current_year AND month_show = $current_month AND day_show >= $current_day) 
              OR (year_show > $current_year) 
              ORDER BY year, month, day LIMIT 0, $maxnum";
              
              $paramra = array(
                'hostvar' =>$dbhost, 
                'uservar' => $dbuser, 
                'passvar' => $dbpass, 
                'databasevar'=> $dbname, 
                'sql' =>$query,
                'chunkName' =>'displayEvents',
                'perPage' => '5',
                'orderby' => 'id',
                'missingValTxt' => '--');
              
              return $modx->runSnippet('loopDBChunk' , $paramra);
              ?>
              


              The call to loopDBChunk include four additional parameters, which are pulled from a config file :
              the database host, user, password and database name.

              The snippet "loopDBChunk" was edited near the end to include the lines with my initials :
              $ldParam['footer'] = isset($footer) ? $footer : '';
              
              $ldParam['thehost'] = isset($hostvar) ? $hostvar : '';  //MattC
              $ldParam['theuser'] = isset($uservar) ? $uservar : '';  //MattC
              $ldParam['thepass'] = isset($passvar) ? $passvar : '';  //MattC
              $ldParam['thedatabase'] = isset($databasevar) ? $databasevar : '';  //MattC
              
              require_once($ldPath . 'LoopDBChunk.php');
              


              (Take note that the name of the array variable begins with a lower case "L", not an upper case "I". This can cause confusion and a lot of wasted time depending on what font you are using. Trust me - it took two days to figure out why only the most recent added variables weren’t getting passed all the way through!)

              Finally "LoopDBChunk.php" was edited to include these initialed lines as well :
              class LoopDBChunk {
              
              	var $hostvar = ''; //MattC
              	var $uservar = ''; //MattC
              	var $passvar = ''; //MattC
              	var $databasevar = ''; //MattC
              
              	var $tableName = '';
              <snip>
              	function LoopDBChunk($paramArray)
              	{
              		$this->hostvar = $paramArray['thehost'];  //MattC
              		$this->uservar = $paramArray['theuser'];  //MattC
              		$this->passvar = $paramArray['thepass'];  //MattC
              		$this->databasevar = $paramArray['thedatabase'];  //MattC
              
              		$this->tableName = $paramArray['table'];
              <snip>
              				$query .= ' ORDER BY ' . $this->orderby;
              			}
              		}	
              
              		mysql_connect($this->hostvar,$this->uservar,$this->passvar) OR DIE ('Unable to connect to database! Please try again later.'); //MattC
              		mysql_select_db($this->databasevar) or die( "Unable to select database");  //MattC
              				
              		//$rs = $modx->db->query($query);
              		$rs = mysql_query($this->sql);  //MattC
              
              		//$numRows = $modx->db->getRecordCount($rs);
              		$numRows = mysql_num_rows($rs);  //MattC
              
              		if($this->perPage > 0) 
              		{
                 		$from = $pageStart - 1;
                 		$query .= ' LIMIT ' . $from . ', ' . $this->perPage;
                 		}
              		
              		//$rs = $modx->db->query($query);
              		$rs = mysql_query($this->sql);  //MattC
              		// echo $query . '<br/>';
              		$this->chunk = $modx->getChunk($this->chunkName);
                    
                    		$i = 0;
              		//while( $row = $modx->db->getRow($rs) ) 
              		while( $row = mysql_fetch_assoc($rs) )  //MattC
              		{
              			$output .= $this->getChunkReplaced($row, $i);	
                       		$i++;		
              		}
              
              		mysql_close();  //MattC
              <snip>
              

              There could probably be more/better error trapping, or even more elegant ways to accomplish the same thing. But I think this will work and I hope it helps someone else.

              Matt
                • 24673
                • 3 Posts
                Any way to make one of the data fields clickable so when I do this it redirects to another page with more info from the same database row?
                  • 18913
                  • 654 Posts
                  Yes, if I understand what you are asking. Specifically, in the chunk used to display records (in the example above it’s called displayEvents) I can add this:
                  <div><form method="post" action='<web address>/index.php?id=94&testparam=[+id+]'>
                  <input type='Submit' name='submit' value='More...' >
                  </form></div>

                  which will create a button labeled "More..." as part of each record displayed. When selected, this redirects to the page represented by document ID 94, with the url now containing the variable "testparam". It’s value has been set to the record id ("id" was a field in the database) of the entry selected.

                  For testing, I put a snippet on this page which contained the following code :
                  $testparam = $_GET['testparam'];
                  if ($testparam != NULL) {
                    echo $testparam;
                  }
                  else {
                    echo "No param found";
                  }
                  

                  which correctly displayed the record id.

                  So you could then take this record id, construct a new query, retrieve whatever else you needed, format them accordingly, and off you go. With different versions of "displayEvent" (or, rather, the equivalent routine for formatting), this could be a nested process, I’d guess.

                  A more secure way I suppose would be to have the button set a session variable. But I don’t know how to do that - if anyone can provide an example, that would be great.

                  Hope this helps,
                  MattC
                    • 24673
                    • 3 Posts
                    Many thanks! MattC laugh

                    sorry if I wasnt clear enough, english isnt my native language and besides being able to understand it fairly well
                    my writung is very poor.

                    This is my first time messing with php and sql and I dont know any programming language (only a tiny bit of css and html)
                    I came from Joomla and Im amazed of how flexible modx is, its a shame it doesnt have as many followers as other cmss.

                    I was able to output the same results of your example (at first I was getting errors because I didnt change the <web adress> part, but was able to figure it)

                    Now I will try to read some php docs to see if I figure how to use the output to do what I want,
                    I think I need to put some kind of code that will load my database table then get the output of this page and compare with the fields from one a determined column of my table then if they match load the entire row.

                    Thanks again
                      • 28042 ☆ A M B ☆
                      • 24,524 Posts
                      What you’ll want is a SELECT query, using a WHERE clause like
                      SELECT * from 'table' WHERE 'field' = 'output'

                      http://dev.mysql.com/doc/refman/5.0/en/selecting-rows.html
                      Or if you just want to check for certain words or phrases
                      SELECT * from 'table' WHERE 'fieldname' LIKE '%output%'

                      http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html

                      You can use the MODx DBAPI for this
                      http://wiki.modxcms.com/index.php/API:DBAPI:select
                        Studying MODX in the desert - http://sottwell.com
                        Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                        Join the Slack Community - http://modx.org