We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 20080
    • 17 Posts
    I’m trying to insert a record into a db table. All fields go in except for the fields I get from functions. I have several
    functions in one snippet.

    I know this is probably not the best practice, but here it goes.

    1.) I have a form that posts uning jquery/ajax.
    2.) it posts to /index.php?id=124 (cached or uncached = same error)
    a.)id 124 contains snippet [!CnbPhp!]
    3.) There are two parts to [!CnbPhp!] depending on the post values $_POST[’search’] or $_POST[’insert’]
    a.) searches for a record from the database & returns json (works fine)
    b.) retrieves $_POST variables and inserts into DB returns json confirmation (partially working)

    In step 3.b I process some of the $_POST variables with functions with global variables.

    This works when developing on my local machine using regular php scripts, but as soon as I copy them into a snippet
    modx (the only change is the DBAPI for db query, still using same insert fields and values) eveythign except the data
    that should have been processed by a function gets inserted. No errors. Still returns json data with confirmation of inserting
    record into db.

    Any help or explanation woudl be appreciated.
    //assume the post sends this
    	$_POST['product'] = 'DM-CFB1G139';
    		
    	//define variables 
    	//(tried it with or without definine these outside the function. Same result
    	$myPrice = '';
    	$myQty = '';
    
    	//define my function with global variables
    	function myOffers(){
    		global $myPrice, $myQty;
    		
    		switch ($_POST['product']):
    			case 'DM-CFB1G139':
    				$myPrice = '39.99'; 
    				$myQty = '1'; 
    				break;
    			case 'DM-CFB1G139AS':
    				$myPrice = '39.99'; 
    				$myQty = '1'; 
    				break;
    			case 'DM-CFTRY29':
    				$myPrice = '0.00'; 
    				$myQty = '1'; 
    				break;
    			case 'DM-CFTRY29AS':
    				$myPrice = '0.00'; 
    				$myQty = '1'; 
    				break;
    			default:
    				$myPrice = '0.00'; 
    				$myQty = '1'; //Should be 0, but set to 1 just to test, no differnce
    		endswitch;
    	}
    
    	//call the function
    	myOffers();
    	
    	//fields going into DB
    	$fname = $_POST['fname'];
    	$lname = $_POST['lname'];
    	$product = $_POST['product'];
    	
    	//fields for sql statment
    	$insertFields = 'FNAME, 
    						LNAME, 
    						PRODUCT,
    						PRICE,
    						QTY';
    						
    	//insert values for sql statement
    	$insertValues ="'".$fname."',"; //First Name, 
    	$insertValues .="'".$lname."',"; //LAst name,
    	$insertValues .="'".$product."',"; //Product, 
    	$insertValues .="'".$myPrice."',"; //Price
    	$insertValues .="'".$myQty."'"; //Qty
    	
    	//insert into db
    	$sql = "INSERT INTO  modx_table1 (".$insertFields.") VALUES(".$insertValues.") ";
       	$rs = $modx->db->query($sql);
    	
    	//Confirmation ID
    	if(!$rs){
    		$key = 'ERROR INSERTING RECORD.';
    	} else {   
    		 //now get the id
    		 $key = $modx->db->getInsertId();
    	} 
    	
    	//just for reference my normal db call outside of modx.
    	//mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
    	//mysql_select_db("modx") or die(mysql_error());
    
    	// Insert a row of information into the table "example"
    	//$insert = mysql_query("INSERT INTO  modx_table1 
    	//(".$insertFields.") VALUES(".$insertValues.") ") 
    	//or die(mysql_error());
    		
    	//$key = mysql_insert_id();
    


    Here is some code. Maybe there is soemthign blatently wrong with it (any sytax errors are jsut from me typing it in this post.)
    Like I said it works perfectly fine outside of modx. I simply copy and paste the code into a snippet with different DB call
      www.DMSalesSolutions.com New Site using Modx (still learning though)
    • Is there just the one instance of the snippet on the page in question?

      I would avoid using the global namespace:

      //assume the post sends this
      	$_POST['product'] = 'DM-CFB1G139';
      
      	//define my function with global variables
      	function myOffers(){
      		
      		switch ($_POST['product']):
      			case 'DM-CFB1G139':
      				$myPrice = '39.99'; 
      				$myQty = '1'; 
      				break;
      			case 'DM-CFB1G139AS':
      				$myPrice = '39.99'; 
      				$myQty = '1'; 
      				break;
      			case 'DM-CFTRY29':
      				$myPrice = '0.00'; 
      				$myQty = '1'; 
      				break;
      			case 'DM-CFTRY29AS':
      				$myPrice = '0.00'; 
      				$myQty = '1'; 
      				break;
      			default:
      				$myPrice = '0.00'; 
      				$myQty = '1'; //Should be 0, but set to 1 just to test, no differnce
      		endswitch;
      		return array($myPrice, $myQty);
      	}
      
      	//call the function
      	list($myPrice, $myQty) = myOffers();
      	
      	//fields going into DB
      	$fname = $_POST['fname'];
      	$lname = $_POST['lname'];
      	$product = $_POST['product'];
      	
      	//fields for sql statment
      	$insertFields = 'FNAME, 
      						LNAME, 
      						PRODUCT,
      						PRICE,
      						QTY';
      						
      	//insert values for sql statement
      	$insertValues ="'".$fname."',"; //First Name, 
      	$insertValues .="'".$lname."',"; //LAst name,
      	$insertValues .="'".$product."',"; //Product, 
      	$insertValues .="'".$myPrice."',"; //Price
      	$insertValues .="'".$myQty."'"; //Qty
      	
      	//insert into db
      	$sql = "INSERT INTO  modx_table1 (".$insertFields.") VALUES(".$insertValues.") ";
         	$rs = $modx->db->query($sql);
      	
      	//Confirmation ID
      	if(!$rs){
      		$key = 'ERROR INSERTING RECORD.';
      	} else {   
      		 //now get the id
      		 $key = $modx->db->getInsertId();
      	} 
      	
      	//just for reference my normal db call outside of modx.
      	//mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
      	//mysql_select_db("modx") or die(mysql_error());
      
      	// Insert a row of information into the table "example"
      	//$insert = mysql_query("INSERT INTO  modx_table1 
      	//(".$insertFields.") VALUES(".$insertValues.") ") 
      	//or die(mysql_error());
      		
      	//$key = mysql_insert_id();
      
        Mike Schell
        Lead Developer, MODX Cloud
        Email: [email protected]
        GitHub: https://github.com/netProphET/
        Twitter: @mkschell
      • Do you have error logging enabled? If you’re getting errors here, they should show up in your Apache or PHP logs. It’d be worth checking your MODx logs too for that matter.

        Did you put "global $modx" anywhere in your snippet so you inherit the MODx object?

        This is real dangerous stuff you’re doing though... are you doing any data validation on this stuff?
          • 20080
          • 17 Posts
          @netProphET
          yes. Just called once on doc 124

          hmm I’ll try your suggestion.

          @Everett
          Have not looked at error logs. Since it appears to be working, except not inserting those fields
          so I;m assuming they are not even being called. You know what happens when you assume. I’lltake a look.

          I did try using the global $modx , but didnt make a difference.
          Update: Nothign in Modx Logs.
            www.DMSalesSolutions.com New Site using Modx (still learning though)
            • 20080
            • 17 Posts
            Thanks netProphet
            You suggestion worked and gets the data into the db.

            I also tried taking the switch case out of the function and it also works. I wish I knew the reason why it would not work in modx, but works outside of it.

            //assume the post sends this
            	$_POST['product'] = 'DM-CFB1G139';
            	$_POST['fname'] = 'Test';
            	$_POST['lname'] = 'Snippet';
            		
            	//no more function with global variables		
            		switch ($_POST['product']):
            			case 'DM-CFB1G139':
            				$myPrice = '39.99'; 
            				$myQty = '1'; 
            				break;
            			case 'DM-CFB1G139AS':
            				$myPrice = '39.99'; 
            				$myQty = '1'; 
            				break;
            			case 'DM-CFTRY29':
            				$myPrice = '0.00'; 
            				$myQty = '1'; 
            				break;
            			case 'DM-CFTRY29AS':
            				$myPrice = '0.00'; 
            				$myQty = '1'; 
            				break;
            			default:
            				$myPrice = '0.00'; 
            				$myQty = '1'; //Should be 0, but set to 1 just to test, no differnce
            		endswitch;
            	
            
              www.DMSalesSolutions.com New Site using Modx (still learning though)
            • I think it’s because snippet code does not run in the global namespace in the first place.
              So before, you were addressing the globals in your function, then outside of the function, the variables were not actually globals as they may have seemed. To make predictable use of globals in a snippet, you really need to address them via the $GLOBAL array e.g. $GLOBAL[’myPrice’]
                Mike Schell
                Lead Developer, MODX Cloud
                Email: [email protected]
                GitHub: https://github.com/netProphET/
                Twitter: @mkschell
              • I think Everett’s right, by the way.
                Passing unmodified $_POST variables right into your SQL opens you right up to SQL injection attacks.
                (Or perhaps you had simplified the script for illustration, in which case, ignore this!)
                You would at least do this:
                $fname = $modx->db->escape($_POST['fname']);
                
                  Mike Schell
                  Lead Developer, MODX Cloud
                  Email: [email protected]
                  GitHub: https://github.com/netProphET/
                  Twitter: @mkschell
                  • 20080
                  • 17 Posts
                  Sorry.

                  yes. I am escaping the POSTs on production, but not on my local dev machine.

                  Thanks for your help. Both of you.

                    www.DMSalesSolutions.com New Site using Modx (still learning though)