We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
  • Quote from: presson83 at Feb 19, 2010, 05:55 PM

    I’ve got checkboxes in my form. When it saves the form data into the DB it just prints the word "ARRAY". How do you save the array of info from a form with checkboxes?

    Try changing the name of your checkboxes to include "[]" at the end.

    E.g.
    name="colors[]" value="Red"
    name="colors[]" value="Blue"
    name="colors[]" value="Green"
      Mike Reid - www.pixelchutes.com
      MODx Ambassador / Contributor
      [Module] MultiMedia Manager / [Module] SiteSearch / [Snippet] DocPassword / [Plugin] EditArea / We support FoxyCart
      ________________________________
      Where every pixel matters.
      • 13197
      • 21 Posts
      I am sorry to revisit this post with a question but I have spent about 10 hours struggling with what I suspect is a really simple issue. I am very new to PHP and SQL.
      I am using MODx 1.0.2, eForm 1.4.4.6 and eForm2db 0.1 Beta 1.
      I can get eForm2db to place data into my MODx database using the code quoted below. However, I wish to put the data into another database. The other database is on the same server and has the same user name and password as the MODx database.
      The MODx database is called: william_modx
      The table is called: modx_customers
      The alternative database is called: william_data
      the alternative table in this database is called: modx_customers
      <?php
      function eForm2db( &$fields )
      	{
      		/*---------------------------------------------------------------		
      		eForm2db 
      		Version: 0.1 [Beta 1]
      		Author: pixelchutes
      		---------------------------------------------------------------
      		Requirements:
      			eForm 1.4+
      		---------------------------------------------------------------
      		Use:
      			- Takes validated eForm submittal data for use with the MODx DBAPI extender class.								
      			- Easily process database records referencing your form submission data:				  
      			  + INSERT new records to a table of your choice				  
      			  + UPDATE existing records if you'd prefer				  
      			  + DELETE records based on form submittal criteria				  
      			  + Form a query and return its record set as XML using $modx->db->getXML				  
      			  + Query a table's MetaData using $modx->db->getTableMetaData, followed by an update query
      			    on only the form fields that are named after table columns!				    
      			  + and much more! 
      		---------------------------------------------------------------*/
      
      		// Bring needed resources into scope
      		global $modx, $table_prefix;
      
      		// Init our array
      		$dbTable = array(); // key = DB Column; Value = Insert/Update value
      		$dbTable['name'] = $fields['name'];
      		$dbTable['name2'] = $fields['name2'];
      		$dbTable['email'] = $fields['email'];
      		$dbTable['comments'] = $fields['comments'];
      		$dbTable['mailing'] = $fields['mailing'];
      
      		// Insert field/value pairs to insert/update in our table
      		//$dbTable[name] = $fields[first_name].' '.$fields[last_name]; // Merge two form fields together
      		//$dbTable[datetime] = date( 'YmdHis', strtotime( $fields[postdate] ) ); // Massage the postdate timestamp to be MySQL insert friendly
      
      
      		INSERT - $dbQuery = $modx->db->insert( $dbTable, $table_prefix . 'customers' );
      		// UPDATE - $dbQuery = $modx->db->update( $dbTable, $table_prefix . 'updateTableName' );
      		// DELETE - $dbQuery = $modx->db->delete( $table_prefix . 'deleteFromTableName', 'some_field = 1 AND name=\''.$dbTable[name].'\'', '' );
      		// etc...
      				
      		// Run the db insert query
      $dbQuery = $modx->db->insert( $dbTable, $table_prefix . 'customers' );
      		return true;
      	}
      	// Return empty string
      	return $sql;
      ?>

      Having looked at the DBAPI instructions it looks like I ougt to be able to insert
      $ds = $modx->db->select('*','william_data.customers');
      
      or
      $ds = $modx->db->select('*','william_data.modx_customers');
      
      to get this to put the data into the alternative database. However, I am not sure if this code is correct or exactly where to put it, or if there is an additional change I need to make. All experiments so far have resulted in errors or blank pages.
      If anyone can help I would be very grateful. Thanks, Andy
        • 3749
        • 24,544 Posts
        Quote from: itough at Feb 26, 2010, 03:32 PM

        Having looked at the DBAPI instructions it looks like I ougt to be able to insert
        $ds = $modx->db->select('*','william_data.customers');
        
        or
        $ds = $modx->db->select('*','william_data.modx_customers');
        
        to get this to put the data into the alternative database. However, I am not sure if this code is correct or exactly where to put it, or if there is an additional change I need to make. All experiments so far have resulted in errors or blank pages.
        If anyone can help I would be very grateful. Thanks, Andy


        Did you try this:

        $ds = $modx->db->select('*','william_modx.modx_customers');
        
        and
        $ds = $modx->db->select('*','william_data.modx_customers');
        


        The part before the dot is the name of the DB, the part after it is the name of the table.
          Did I help you? Buy me a beer
          Get my Book: MODX:The Official Guide
          MODX info for everyone: http://bobsguides.com/modx.html
          My MODX Extras
          Bob's Guides is now hosted at A2 MODX Hosting
          • 13197
          • 21 Posts
          Hi Bob, Thanks for looking at this. I have often used your site when trying to expand my MODx abilities! In my post I mentioned that I have tried using:
          $ds = $modx->db->select('*','william_data.customers');

          OR
          $ds = $modx->db->select('*','william_data.modx_customers');

          You have asked if I have tried:
          $ds = $modx->db->select('*','william_data.customers');

          AND
          $ds = $modx->db->select('*','william_data.modx_customers');

          As I have tried them both already, Is my mistake that I should be using them both together?
          Or am I simply placing them in the wrong part of the snippet? Where should this code go within the snippet?

          Thanks, Andy
            • 3749
            • 24,544 Posts
            Sorry, I think I misread your message. One or the other is correct -- I suspect the one with the full table name (including the prefix), but I’m not sure. I’m afraid the docs aren’t explicit enough.

            Also, I’ve been working in Revolution and am really rusty on the old way of doing DB access.

            What you’re trying to do should work, but the username and password need to be the same for the alternate table.


            There’s an example here that might help. If you can’t get anywhere with your code, you might try the method here where you change the connection to the other DB with $modx->db->connect(credentials here), do the work, then change it back to the MODx DB with $modx->db->connect() with no arguments.

            http://wiki.modxcms.com/index.php/API:DBAPI:connect

            Check to make sure the connection was successful with this: http://wiki.modxcms.com/index.php/API:DBAPI:isConnected

            Here’s the full list of DBAPI functions: http://wiki.modxcms.com/index.php/API:DBAPI

            As a last resort, you could try this and have two separate DB connections open at the same time: http://wiki.modxcms.com/index.php/API:DBAPI:config

            Then you’d have two separate DB objects:

            $modx->db   (the default DB)
            
            $myDb = new DBAPI('12.23.4.5','mydb', 'username','password', 'myprefix_', '[charset]');


            Then $modx->db->select() for one and $myDb->select() for the other.

            Hope this helps.

            Bob
              Did I help you? Buy me a beer
              Get my Book: MODX:The Official Guide
              MODX info for everyone: http://bobsguides.com/modx.html
              My MODX Extras
              Bob's Guides is now hosted at A2 MODX Hosting
              • 13197
              • 21 Posts
              Thanks for this Bob. I will follow up these leads later over the weekend. I’ll let you know how I get on. It’s good of you to take the time to help. Andy
                • 13197
                • 21 Posts
                I think that previously I was putting the database select code in the wrong place.
                Adding this does seem to get a connection to the database
                // Bring needed resources into scope
                $ds = $modx->db->select('*','william_data.modx_customers');
                		global $modx, $table_prefix;


                However it results in this error
                Fatal error: Call to a member function select() on a non-object in /home/william/www/dev/manager/includes/document.parser.class.inc.php(770) : eval()'d code on line 23


                Line 23 of this document reads
                        $this->loadedjscripts= array ();
                


                It is in this context
                 // constructor
                    function DocumentParser() {
                        $this->loadExtension('DBAPI') or die('Could not load DBAPI class.'); // load DBAPI class
                        $this->dbConfig= & $this->db->config; // alias for backward compatibility
                        $this->jscripts= array ();
                        $this->sjscripts= array ();
                        $this->loadedjscripts= array ();
                        // events
                        $this->event= new SystemEvent();
                        $this->Event= & $this->event; //alias for backward compatibility
                        $this->pluginEvent= array ();
                        // set track_errors ini variable
                        @ ini_set("track_errors", "1"); // enable error tracking in $php_errormsg
                    }

                I don’t know if this sheds any light on what I am doing wrong.
                Perhaps I need to review why I am trying to do this? My concern is that I don’t want anyone ’out there’ to be able to use a feedback form to add content to my main MODx database. It seems more secure to use a separate database? Am I being unnecessarily paranoid?


                  • 3749
                  • 24,544 Posts
                  The document parser is just executing your code using eval() so line 23 is in your code (and the line number may not be accurate).

                  The error message is most likely saying that the $modx object is not available where you’re calling select() (probably somewhere around line 23 of your code).

                  If you’re doing that in a function, you need to have global $modx as the first line of the function. Sometimes that still doesn’t work and you have to pass $modx as an argument to the function.

                  Feel free to post your complete snippet here if you’re still stuck.
                    Did I help you? Buy me a beer
                    Get my Book: MODX:The Official Guide
                    MODX info for everyone: http://bobsguides.com/modx.html
                    My MODX Extras
                    Bob's Guides is now hosted at A2 MODX Hosting
                    • 16642
                    • 2 Posts
                    Quote from: Onesmarthost at Sep 20, 2007, 10:10 AM

                    I’ve been doing some cool stuff with eform2db to save data from a form, and also load it into the form, perhaps these examples will help you:

                    Hello Aaron,

                    I was playing with eform2db and I found your post very interesting and detailed as it’s my first try with eform2db. Then I realized I know you (I am actually the designer of coms.com + comscall + purestyleonline.com)

                    I tried to implement the code you provided but I think I am missing something. "Add a Venue" works well for me but not "Show Venues" which seems always returning the error message:
                    MODx encountered the following error while attempting to parse the requested resource:
                    « PHP Parse Error »

                    PHP error debug
                    Error: mysql_num_rows(): supplied argument is not a valid MySQL result resource
                    Error type/ Nr.: Warning - 2
                    File: /nfs/c06/h02/mnt/88664/domains/locallinkbuilding.com/html/manager/includes/document.parser.class.inc.php(770) : eval()’d code
                    Line: 6


                    I realized that you use 2 tables: $sql = "SELECT *,modx_rsvp_venues.id as venue_id FROM $dbase.".$table_prefix."rsvp_venues,".$table_prefix."rsvp_events WHERE modx_rsvp_events.member_id = ’" .$usernameid ."’ AND modx_rsvp_venues.member_id = ’" .$usernameid ."’ ORDER BY venue_order ASC";

                    So, I guess it’s because we won’t have your db tables. What are your thoughts?
                    Although I tried to use the 2 following tables, "Show Venues" doesn’t want to work.

                    CREATE TABLE `modx_rsvp_venues` (
                      `id` int(10) unsigned NOT NULL auto_increment,
                      `member_id` varchar(50) NOT NULL,
                      `venue_address` varchar(255) NOT NULL,
                      `venue_postcode` varchar(12) NOT NULL,
                      `venue_time` varchar(40) NOT NULL,
                      PRIMARY KEY  (`id`)
                    )
                    
                    CREATE TABLE `modx_rsvp_events` (
                      `venue_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                      `member_id` varchar(50) NOT NULL,
                      PRIMARY KEY (`venue_id`)
                    )



                    Could you please provide us with the tables you used in your script ?

                    Pierre Ogier
                    POW Websites/SEO Expert
                      • 19328
                      • 433 Posts
                      Hi there,

                      I’ve been trying for hours to get an adjusted version of the ’venues’ example to work. For my website, I only need the edit-part, because I want to use it to let users edit some of their profile-information (like e-mailadress). Because I want manager users to do this on the frontend, I can’t use an existing snippet like WebLoginPE because all the snippets that do this are for web users. (as far as I know of!)

                      I’ve got it to display the information of the logged in Manager user (on frontend), but I can’t get it to update if anything is changed in the form. It’s like the ’isPostBack’ variable is never set to true.

                      This is my code:

                      The call on the page ’Edit profile’:
                      [[populateUserForm]]
                      [[Users2db]]
                      [[eForm?formid=`user_form` &protectSubmit=`0` &tpl=`user_form` &noemail=`1` &eFormOnBeforeMailSent=`Users2db` &eFormOnBeforeFormParse=`populateUserForm`]]


                      [[populateUserForm]]
                      <?php
                      function populateUserForm(&$fields, &$templates) {
                                 global $modx;
                                 $userinternalkey = $_SESSION['mgrInternalKey'];
                                //$userform_id = $_GET['id'];
                                 $evt =$modx->event; // The Snippet call event (not eFormOnBeforeFormParse event)
                                 // Replicate $isPostBack variable
                      $validFormId = ($evt->params['add_user'] == $_POST['add_user']);
                      $isPostBack = ($validFormId && count($_POST) > 0); 
                      
                      // Some tests
                      echo "userinternalkey=".$userinternalkey."<br>";
                      echo "submit set=".isset($_POST['submit'])."<br>";
                      echo "validFormId=".$validFormId."<br>";
                      echo "count post =".count($_POST)."<br>";
                      echo "is PostBack=".$isPostBack."<br>";
                      
                      //select uit db
                      if (!$isPostBack) {
                      echo "no postback";              
                      // Check for NOT postback, cuz we want to populate an empty form
                                    // Also, make sure we have an id greater than 0
                                    $rs = $modx->db->select('`id`,`internalKey`, `fullname`, `email`, `phone`','modx_user_attributes','internalKey="'. $userinternalkey. '"');
                                     $row = $modx->db->getRow($rs); // Get the single row
                                     if (!empty($row)) // Does the row have data?
                                        $fields[userform_id] 	= $row[id];
                      		  $fields[fullname] 	= $row[fullname]; // Copy the data over to the fields variable
                                        $fields[email] 	= $row[email];
                                        $fields[phone] 	= $row[phone];
                                     } else {           
                      echo "postback";  
                      // The form has beed posted, let's not disturb the data.
                                     }
                                    
                       return true; // A value of false will stop the eForm parser
                                 }
                      ?>


                      [[Users2db]]

                      <?php
                      function Users2db( &$fields )
                         {
                            /*---------------------------------------------------------------      
                            eForm2db
                            Version: 0.1 [Beta 1]
                            Author: pixelchutes */
                            
                            // Bring needed resources into scope
                            global $modx, $table_prefix;
                            $usernameid = $_SESSION['mgrInternalKey'];
                            $vid = $fields[userform_id];
                      
                            	// Init our array
                            	$dbTable = array(); // key = DB Column; Value = Insert/Update value
                            	//$dbTable[id] = $fields[id];
                      	//$dbTable[internalKey] = $usernameid;
                      	$dbTable[fullname] = $fields[fullname];
                            	$dbTable[email] = $fields[email];
                            	$dbTable[phone] = $fields[phone];
                            
                      
                            if ($vid != "") {
                               $dbQuery = $modx->db->update($dbTable, 'modx_user_attributes', 'internalKey = " ' . $usernameid .' " ' );      
                               return true;
                            } else {
                               $dbQuery = $modx->db->insert( $dbTable, 'modx_user_attributes' );      
                               return true;
                            }
                      }
                      ?>


                      And the form itself:

                      {{user_form}}

                      <span style="color:#900;">[+validationmessage+]</span>
                      <br>
                      <form method="post" name="user_form" id="user_form" class="cssform" action="[~[*id*]~]">
                      
                      <p>
                      <label for="fullname">Full name:</label>
                      <input type="text" name="fullname" id="fullname" eform="fullname:string:1" value="[+fullname+]" size="20" maxlength="30" />
                      </p>
                      
                      <p>
                      <label for="venue_address"> Email:</label>
                      <input type="text"name="email" value="[+email+]" id="email"  eform="email:email:1" size="20" maxlength="30" />
                      </p>
                      
                      <p>
                      <label for="phone"> Phone:</label>
                      <input type="text" name="phone" id="phone" value="[+phone+]" eform="phone:string:1" size="20" />
                      </p>
                      
                      <input type="text"style="display:none;" id="userform_id" name="userform_id" value="[+userform_id+]" eform="userform_id::0"/>
                      
                      <p>
                      <input type="submit" name="submit" class="button" value="Gegevens wijzigen" />
                      <br>
                         </fieldset>
                      </p>
                      </form>


                      I must be overlooking something obvious, because it’s almost the same as the example.
                      Also, I don’t really understand how this line of code works:
                      $validFormId = ($evt->params['add_user'] == $_POST['add_user']);

                      I don’t have ’add_user’ in the form, but I also don’t see it in the example form. Should I put something else there?

                      Thanks in advance for any help!