Fork me on GitHub

How do I 'INSERT' sql from within a PNINIT function??  Bottom

  • Okay this is what im trying to do, and im having real hassles:

    Populate a table within my mysql DB using data submitted on template page of the new 'Example' module's interactive initialization functions (within pninit.php). I'm using PN .761

    The function i am concerned with is:

    example_init_step2() to be exact.


    Code

    function example_init_step2()
    {

    // This is part two of the interactive installation procedure. We will ask the user for some basic data now. After collecting the data, we store them session vars.

        // Check permissions
        if (!pnSecAuthAction(0, '::', '::', ACCESS_ADMIN)) {
            return pnVarPrepHTMLDisplay(_MODULENOAUTH);
        }


    // submit is set if the users sends his data. We can use the same function here for presenting our form and handle the users input.


     $submit = pnVarCleanFromInput('submit');
        if(!$submit) {

           
    // submit is not set, show the form now

            $pnr =& new pnRender('example');
            $pnr->caching = false;
            return $pnr->fetch('example_init_step2.htm');
     } else {


    // submit is set, read the data and store them.

     if (!pnSecConfirmAuthKey()) {
    pnSessionSetVar('errormsg', pnVarPrepHTMLDisplay(_BADAUTHKEY));
                return pnRedirect(pnModURL('Modules', 'admin', 'view'));
            }


    // submit is set, assign the post data into string variables

    list($firstname, $lastname, $company, $email, $activate ) = pnVarCleanFromInput('firstname', 'lastname', 'company', 'email', 'activate');
       
    // We do not store the values directly in the mod vars but put them in to a session var first. This will be read in the _init function. So we keep backwards compatible with .750 or earlier

            pnSessionSetVar('example_firstname', $firstname);
            pnSessionSetVar('example_lastname', $lastname);
            pnSessionSetVar('example_company', $company);
            pnSessionSetVar('example_email', $email);
           
            $activate = (!empty($activate)) ? true : false;
           
    $dbconn  =& pnDBGetConn(true);
    $pntable =& pnDBGetTables();
    $example_admin_data_table  = &$pntable['example_admin_data'];
    $example_admin_data_column = &$pntable['example_admin_data_column'];
       
    $dict = &NewDataDictionary($dbconn);
    $taboptarray =& pnDBGetTableOptions();   
       
    $sql = "INSERT INTO $example_admin_data_table VALUES ( '$firstname', '$lastname' , '$company' ,'$email' )";


    // I use the two lines below for testing the sql output.
    // echo $sql;
    // die();


    $result = $dbconn->Execute($sql);
         
    }



    // we are ready now and redirect to the function that is responsible for installing a module

    return pnRedirect(pnModURL('example', 'init', 'step3', array('activate' => $activate)));
    }


    The SQL that's being output to the screen is good to go, I can initialize the module.. and all the tables and indexes are being created okay... but the data just isn't populating the tables at this point. Does anyone know how i can write the info that's in those variables (the ones i grabbed from the form's submit action) and write them to my database??

    I want to take info submitted at the initialization stage and add it to the database tables using the adodb dictionary syntax, the tables have already previously created by the function pninvoice_init().

    Any help would be much appreciated.
  • Take a look at the pninit in the admin module. It shows the new way of doing inserts. Here is an example.

    Code

    // Get datbase setup - note that both pnDBGetConn() and pnDBGetTables()
        // return arrays but we handle them differently.  For pnDBGetConn()
        // we currently just want the first item, which is the official
        // database handle.  For pnDBGetTables() we want to keep the entire
        // tables array together for easy reference later on
        $dbconn =& pnDBGetConn(true);
        $pntable =& pnDBGetTables();

        // It's good practice to name the table and column definitions you
        // are getting - $table and $column don't cut it in more complex
        // modules
        $example_admin_data_table  = &$pntable['example_admin_data'];
        $example_admin_data_column = &$pntable['example_admin_data_column'];

        $record = array();
        $record['table_id']         = $dbconn->GenID($example_admin_data_table);
        $record['firstname']         = $firstname;
        $record['lastname']        = $lastname;
        $record['company'] = $company;
        $record['email'] = $email;
        // Select an empty record from the database
        $sqltest = 'SELECT * FROM  '. $example_admin_data_table . ' WHERE '.$example_admin_data_column['table_id'].' = -1';
        $rs =& $dbconn->Execute($sqltest);

        // Pass the empty recordset and the array containing the data to insert
        // into the GetInsertSQL function.
        $insertSQL = $dbconn->GetInsertSQL($rs, $record);

        // Create the new record;
        $dbconn->StartTrans();
        $dbconn->Execute($insertSQL);
        $dbconn->CompleteTrans();
  • Do a error check after your insert :

    Code

    if ($dbconn->ErrorNo() != 0) {
            pnSessionSetVar('errormsg','blabla - '.$dbconn->ErrorMsg());
            return false;
        }


    Might help to determine what is wrong.
  • That returned: Failed to load module Example (at function: "step2")
  • If you've changed the name of the module already, don't forget to replace "example" in the function name. :)
  • Yeh I've made sure all the names are lowercase, and notated correctly..
    Thanks for all your help, i'll be so stoked to get my head around this prob.

    http://phplens.com/a…s.getupdatesql.html

    That link might be helpful. I'm really just trying to insert/update fields.
  • What would cause this statement to trigger the function to output: Failed to load module example (at function: "step2") ?

    Code

    if ($dbconn->ErrorNo() != 0) {
            pnSessionSetVar('errormsg', '_CREATEFAILED'.$dbconn->ErrorMsg());
            return false;
        }


    Do you think it might be to do with permissons?

    here is the permission code that's at the beginning of the function:

    Code

    // Check permissions
        if (!pnSecAuthAction(0, '::', '::', ACCESS_ADMIN)) {
            return pnVarPrepHTMLDisplay(_MODULENOAUTH);
        }



    And then this code is executed if the 'submit' variable evaluates true:

    Code

    // submit is set, read the data and store them.
            if (!pnSecConfirmAuthKey()) {
                pnSessionSetVar('errormsg', pnVarPrepHTMLDisplay(_BADAUTHKEY));
                return pnRedirect(pnModURL('Modules', 'admin', 'view'));
            }
  • Ahh.... icon_rolleyes I just noticed that the actual database tables don't get created in the database until after step3 of the interactive initialization.

    So the order of PN calling the functions (during inialization) is:

    example_init_interactiveinit() =>
    example_init_step2() =>
    example_init_step3() =>
    example_init()

    I'll have to take another approach.
  • Success!! I managed to store 17 values (from the form input in step two) into my database. I Made sure that i cleaned the input using pnVarCleanFromInput(). In step2 I passed the cleaned input values into session variables (plus the pnModURL array - i assume we use both for backward compatibility). Then in the example_init() function (near the end) I retreived and prep'd the variables for DB storage, made sure i used pnVarPrepForStore(). carried out the SQL execution then cleaned up the session vars. Gosh i love it when things work.

This list is based on users active over the last 60 minutes.