We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 29635
    • 361 Posts
    If this has been brought up before, I apologize. Couldn’t find anything.

    I’m looking to simply record the eform values in a CSV file on the server (or potentially in a table in the database). I’m thinking it’d be somewhat easy with the event hooks, but I don’t want to reinvent the wheel if it’s been done before.

    Has anybody done this already? Is anybody interested in this functionality?
    Thanks!
      Need MODx Ecommerce? Try FoxyCart!
      • 7231
      • 4,205 Posts
      Have you checked out eForm2DB?
      http://modxcms.com/forums/index.php?topic=8111.0
        [font=Verdana]Shane Sponagle | [wiki] Snippet Call Anatomy | MODx Developer Blog | [nettuts] Working With a Content Management Framework: MODx

        Something is happening here, but you don't know what it is.
        Do you, Mr. Jones? - [bob dylan]
        • 29635
        • 361 Posts
        That’s exactly what I was looking for. Thanks for the link. I _knew_ there had to be something like that, I just couldn’t find it.
          Need MODx Ecommerce? Try FoxyCart!
          • 29181
          • 480 Posts
          For generating a CSV from information in a database, I can really recommend http://www.phpclasses.org/browse/package/1416.html

          I moved the class information directory to assets/snippets/iam_csvdump and created a snippet in the manager that emulated the example, but with the new path, create a database query, call the snippet from some page and done. The entire process took about 5 minutes.

          If you want an example of the snippet call, I’ll post mine, but it’s really nothing heavy.

          All the best,
          Taff
            Adrian Lawley: www.adrianlawley.com
            • 23849
            • 223 Posts
            Taff, could you post an example of your snippet? That would be AWESOME!
              Nick Hoag
              Creative Partner
              The FutureForward

              http://thefutureforward.com
              • 40045
              • 534 Posts
              Lol, you guys have perfect timing =)...I’m doing a bit a more complex eForm thing too...

              I have multiple Forms (varies) on the page (for now 3, but it could be up to let’s say 10...), I want to submit them with AJAX when JS is on but they must also work if JS if off...the whole AJAX stuff was easy done, thanks to jQuery, about 25 lines of code to submit them with AJAX and recieve the validationmessages again (btw. the thankyoumsg)...this was the normal Form --> Send eMail part...

              But I have some forms I don’t need to be sent via eMail, instead the submitted data should be written in a mySQL DB so I found the eForm2db snippet, but I didn’t use it...I just wrote some lines of PHP and put it in a snippet called [[eForm2db_adw]]

              <?php
              require_once ($_SERVER['DOCUMENT_ROOT'] . '/path/to/dblogin.php');
              
              $transform = array(
              	// transform array
              );
              
              $namesRaw = @$_POST['adw_names'];
              $names = strtr($namesRaw, $transform);
              $addressRaw = @$_POST['adw_address'];
              $address = strtr($addressRaw, $transform);
              $cityRaw = @$_POST['adw_city'];
              $city = strtr($cityRaw, $transform);
              $email = @$_POST['adw_email'];
              
              
              	// Connect to mySQL DB
              	$db	= mysql_connect (DB_HOST, DB_USER, DB_PW);
              		if ($db) {
              			// echo 'Verbindung mit der Datenbank erfolgreich hergestellt!';
              		}
              		else {
              			die('Es konnte keine Verbindung mit der Datenbank hergestellt werden! <br /><br />' . mysql_error());
              		}
              	mysql_select_db(DB_NAME) or die ("Die Datenbank konnte nicht gefunden werden!");
              	
              	// Write into mySQL DB
              	$sql = "INSERT IGNORE INTO table_name (`datum`, `names`, `address`, `city`, `email`) VALUES (now(), '$names', '$address', '$city', '$email')";
              	$write_sql = mysql_query($sql) or die("Konnte nicht in die Datenbank schreiben: " . mysql_error());
              	echo
              	'				<div class="thankyou">', "\n",
              	'					<h2>Good Luck!</h2>', "\n",
              	'					<p>Some Text...Lorem Ipsum =)!</p>', "\n",
              	'				</div>', "\n";
              
              	mysql_close($db);
              ?>
              


              this works so far as the AJAX-Posted data is written into the DB as expected the Problem I have is that it doesn’t give a f*** about the eform-validation, the form is validated, no email is sent (enabled the email just for testing) but the data is written in the DB even if the form is empty...

              I call the whole thing with the following calls:

              1) On the page the form is displayed to the user:
              [[eForm? &formid=`adw_form` &subject=`Some subject` &from=`[+adw_email+]` &to=`[email protected]` &sendAsHTML=`1` &tpl=`cfm_form_adw` &report=`cfm_form_adw.emailTpl` &thankyou=`cfm_form_thankYou`]]
              


              2) This is the page the AJAX call posts the data to (separate page in modX)
              [[eForm2db_adw]]
              [[eForm? &formid=`adw_form` &subject=`Some subject` &from=`[+adw_email+]` &to=`[email protected]` &sendAsHTML=`1` &tpl=`cfm_form_adw` &report=`cfm_form_adw.emailTpl` &thankyou=`cfm_form_thankYou` &eFormOnBeforeMailSent=`eForm2db_adw`]]
              


              So the problem I have now is that the data should be written into the DB AFTER the form is correctly validated, when it’s not it should proceed as when a email is sent (meaning: Write to the DB instead of sending an email, nothing else, just do as it was an email but then write it to DB instead of sending it^^...can that be so difficult?=D...)

              Hope I will somehow get this =)...I don’t want to use the modx db because maybe someday there will be other users whith db-login and then I don’t want that they do stuff in the CMS-DB...so I made another DB for Website-related data which is out of the MODx DB (I think also out of the $modx->db etc. stuff...)

              Some hours ago I also had the Problem with the CSV export, didn’t find the script you mentioned (http://www.phpclasses.org/browse/package/1416.html) but got to another solution...

              1) I need a link which I can post on a private site, when it’s clicked, the .csv is served as download
              2) I need "Headers" for the rows in the CSV an not the same name as they are saved in the DB...

              so I got to this:

              this would be the file the link points to...works perfectly...
              <?php
              require_once ($_SERVER['DOCUMENT_ROOT'] . '/path/to/dblogin.php');
              	// Connect to mySQL DB
              	$db	= mysql_connect (DB_HOST, DB_USER, DB_PW);
              		if ($db) {
              			//echo 'Verbindung mit der Datenbank erfolgreich hergestellt!';
              		}
              		else {
              			die('Es konnte keine Verbindung mit der Datenbank hergestellt werden! <br /><br />' . mysql_error());
              		}
              	mysql_select_db(DB_NAME) or die ("Die Datenbank konnte nicht gefunden werden!");
              
              require_once ($_SERVER['DOCUMENT_ROOT'] . '/path/to/mysql2csv.inc.php');
              
              $scriptpath = pathinfo(__FILE__); // use filename to find the name of the mysql table
              $tablename = explode('_', $scriptpath['filename'], 2); // get form prefix with $tablename[0]
              
              $table = 'cfm_' . $tablename[0]; // this is the mySQL tablename which will be exported
              $fields_select = array( // optional array with tablefields & names for the CSV file
              	'datum' 	=> 'Datum',
              	'names' 	=> 'Vor- / Nachname',
              	'address'	=> 'Strasse / Nr.',
              	'city'		=> 'PLZ / Ort',
              	'email'		=> 'eMail Adresse'
              );
              $filename = $tablename[0] . '_gewinner.csv';
              //echo $filename;
              exportMysqlToCsv($table,$filename,$fields_select); // send table name to csv function
              
              // Free memory and close mySQL DB
              mysql_free_result($result); 
              mysql_close($db);
               
              ?>
              


              the mysql2csv.inc.php contains (didn’t write it myself, found it here http://www.ineedtutorials.com/code/php/export-mysql-data-to-csv-php-tutorial/comment-page-2#comment-19027) I just extended it a little for the field names...:

              <?php
               
              function exportMysqlToCsv($table,$filename = 'export.csv',$fields_select = array())
              {
              	$csv_terminated = "\n";
              	$csv_separator = ";";
              	$csv_enclosed = '';
              	$csv_escaped = "\\";
              	
              	$fields = '';
              	if (count($fields_select) > 0) {
              		foreach ($fields_select as $field => $format) {
              			$fields .= $field . ', ';
              		}
              		$fields = substr($fields, 0, -2); // strip trailing comma
              		$sql_query = "select {$fields} from $table";
              	} else {
              		$sql_query = "select * from $table";
              	}
               
              	// Gets the data from the database
              	$result = mysql_query($sql_query);
              	$fields_cnt = mysql_num_fields($result);
               
               
              	$schema_insert = '';
               
              	for ($i = 0; $i < $fields_cnt; $i++)
              	{
              		$field_name = stripslashes(mysql_field_name($result, $i));
              		if (count($fields_select) > 0) {
              			$format_field_name = $fields_select[$field_name];
              			$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $format_field_name) . $csv_enclosed;
              		} else {
              			$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
              		}
              		$schema_insert .= $l;
              		$schema_insert .= $csv_separator;
              	} // end for
               
              	$out = trim(substr($schema_insert, 0, -1));
              	$out .= $csv_terminated;
               
              	// Format the data
              	while ($row = mysql_fetch_array($result))
              	{
              		$schema_insert = '';
              		for ($j = 0; $j < $fields_cnt; $j++)
              		{
              			if ($row[$j] == '0' || $row[$j] != '')
              			{
               
              				if ($csv_enclosed == '')
              				{
              					$schema_insert .= $row[$j];
              				} else
              				{
              					$schema_insert .= $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
              				}
              			} else
              			{
              				$schema_insert .= '';
              			}
               
              			if ($j < $fields_cnt - 1)
              			{
              				$schema_insert .= $csv_separator;
              			}
              		} // end for
               
              		$out .= $schema_insert;
              		$out .= $csv_terminated;
              	} // end while
               
              	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
              	header("Content-Length: " . strlen($out));
              	// Output to browser with appropriate mime type, you choose ;)
              	header("Content-type: text/x-csv");
              	//header("Content-type: text/csv");
              	//header("Content-type: application/csv");
              	header("Content-Disposition: attachment; filename=$filename");
              	echo html_entity_decode($out);
              	exit;
               
              }
               
              ?>
              



              I’m not very happy with this solution, it’s not really elegant =D...but I’m not a PHP coder and I don’t know better =/, just wanted to show the way I "found"...

              I’m very interested in what you guys post here, maybe I can learn something =)...

              EDIT:

              Got it...I just had another look on the eform2db snippet here in the forums, the php is there packed in a function which has to return true, so I did that to and as far as I can say until now it does it’s job perfectly, the form is validated until it’s ok, then written into the db!

              <?php
              function eForm2db_adw() {
              	require_once ($_SERVER['DOCUMENT_ROOT'] . '/path/to/dblogin.php');
              	
              	$transform = array(
              		// transform array
              	);
              	
              	$namesRaw = @$_POST['adw_names'];
              	$names = strtr($namesRaw, $transform);
              	$addressRaw = @$_POST['adw_address'];
              	$address = strtr($addressRaw, $transform);
              	$cityRaw = @$_POST['adw_city'];
              	$city = strtr($cityRaw, $transform);
              	$email = @$_POST['adw_email'];
              	
              	
              		// Connect to mySQL DB
              		$db	= mysql_connect (DB_HOST, DB_USER, DB_PW);
              			if ($db) {
              				// echo 'Verbindung mit der Datenbank erfolgreich hergestellt!';
              			}
              			else {
              				die('Es konnte keine Verbindung mit der Datenbank hergestellt werden! <br /><br />' . mysql_error());
              			}
              		mysql_select_db(DB_NAME) or die ("Die Datenbank konnte nicht gefunden werden!");
              		
              		// Write into mySQL DB
              		$sql = "INSERT IGNORE INTO cfm_adw (`datum`, `names`, `address`, `city`, `email`) VALUES (now(), '$names', '$address', '$city', '$email')";
              		$write_sql = mysql_query($sql) or die("Konnte nicht in die Datenbank schreiben: " . mysql_error());
              	
              		mysql_close($db);
              		return true;
              }
              ?>
              
                • 3749
                • 24,544 Posts
                @lluuuk: Thanks for your contribution!

                It’s people like you that make this such a great community. smiley
                  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