• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP getLastInsertID函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中getLastInsertID函数的典型用法代码示例。如果您正苦于以下问题:PHP getLastInsertID函数的具体用法?PHP getLastInsertID怎么用?PHP getLastInsertID使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了getLastInsertID函数的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: XMLImportSurvey


//.........这里部分代码省略.........
    // TMSW Conditions->Relevance:  Call  LEM->ConvertConditionsToRelevance
    // Import assessments --------------------------------------------------------
    if (isset($xml->assessments)) {
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            unset($insertdata['id']);
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[11]<br />");
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[12]<br />");
            $aQuotaReplacements[$oldid] = getLastInsertID('{{quota}}');
            $results['quota']++;
        }
    }
    // Import quota_members ------------------------------------------------------
    if (isset($xml->quota_members)) {
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $result = Quota_members::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[13]<br />");
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings----------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
开发者ID:ryu1inaba,项目名称:LimeSurvey,代码行数:67,代码来源:import_helper.php


示例2: insert


//.........这里部分代码省略.........
                     if (isset($usesrow)) {
                         $usesleft = $usesrow[0]['usesleft'];
                     }
                     // query for updating tokens
                     $utquery = "UPDATE {{tokens_{$surveyid}}}\n";
                     if (isTokenCompletedDatestamped($thissurvey)) {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed=" . dbQuoteAll($submitdate);
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     } else {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     }
                     $utquery .= "WHERE token=" . dbQuoteAll($_POST['token']);
                     $utresult = dbExecuteAssoc($utquery);
                     //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!<br />\n$utquery<br />\n".Yii::app()->db->ErrorMsg());
                     // save submitdate into survey table
                     $sdquery = "UPDATE {{survey_{$surveyid}}} SET submitdate='" . $submitdate . "' WHERE id={$last_db_id}\n";
                     $sdresult = dbExecuteAssoc($sdquery) or safeDie("Couldn't set submitdate response in survey table!<br />\n{$sdquery}<br />\n");
                 }
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $srid = $last_db_id;
                     $aUserData = Yii::app()->session;
                     //CREATE ENTRY INTO "saved_control"
                     $saved_control_table = '{{saved_control}}';
                     $columns = array("sid", "srid", "identifier", "access_code", "email", "ip", "refurl", 'saved_thisstep', "status", "saved_date");
                     $values = array("'" . $surveyid . "'", "'" . $srid . "'", "'" . $saver['identifier'] . "'", "'" . $password . "'", "'" . $saver['email'] . "'", "'" . $aUserData['ip_address'] . "'", "'" . getenv("HTTP_REFERER") . "'", 0, "'" . "S" . "'", "'" . dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "'" . Yii::app()->getConfig('timeadjust')) . "'");
                     $SQL = "INSERT INTO {$saved_control_table}\n                        (" . implode(',', $columns) . ")\n                        VALUES\n                        (" . implode(',', $values) . ")";
                     /*$scdata = array("sid"=>$surveyid,
                       "srid"=>$srid,
                       "identifier"=>$saver['identifier'],
                       "access_code"=>$password,
                       "email"=>$saver['email'],
                       "ip"=>$aUserData['ip_address'],
                       "refurl"=>getenv("HTTP_REFERER"),
                       'saved_thisstep' => 0,
                       "status"=>"S",
                       "saved_date"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust')));
                       $this->load->model('saved_control_model');*/
                     if (dbExecuteAssoc($SQL)) {
                         $scid = getLastInsertID('{{saved_control}}');
                         $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), gT("Your survey responses have been saved successfully.  You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you."));
                         //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                         $tokens_table = "{{tokens_{$surveyid}}}";
                         if (tableExists($tokens_table)) {
                             $tkquery = "SELECT * FROM {$tokens_table}";
                             $tkresult = dbExecuteAssoc($tkquery);
                             /*$tokendata = array (
                               "firstname"=> $saver['identifier'],
                               "lastname"=> $saver['identifier'],
                               "email"=>$saver['email'],
                               "token"=>randomChars(15),
                               "language"=>$saver['language'],
                               "sent"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust),
                               "completed"=>"N");*/
                             $columns = array("firstname", "lastname", "email", "token", "language", "sent", "completed");
                             $values = array("'" . $saver['identifier'] . "'", "'" . $saver['identifier'] . "'", "'" . $saver['email'] . "'", "'" . $password . "'", "'" . randomChars(15) . "'", "'" . $saver['language'] . "'", "'" . "N" . "'");
                             $SQL = "INSERT INTO {$token_table}\n                                (" . implode(',', $columns) . ")\n                                VALUES\n                                (" . implode(',', $values) . ")";
                             dbExecuteAssoc($SQL);
                             $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), gT("A token entry for the saved survey has been created too."));
                             //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                         }
                         if ($saver['email']) {
                             //Send email
                             if (validateEmailAddress($saver['email']) && !returnGlobal('redo')) {
                                 $subject = gT("Saved Survey Details");
                                 $message = gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
                                 $message .= "\n\n" . $thissurvey['name'] . "\n\n";
                                 $message .= gT("Name") . ": " . $saver['identifier'] . "\n";
                                 $message .= gT("Password") . ": " . $saver['password'] . "\n\n";
                                 $message .= gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n";
                                 $message .= Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}/loadall/reload/scid/{$scid}/loadname/" . rawurlencode($saver['identifier']) . "/loadpass/" . rawurlencode($saver['password']) . "/lang/" . rawurlencode($saver['language']));
                                 if (isset($tokendata['token'])) {
                                     $message .= "/token/" . rawurlencode($tokendata['token']);
                                 }
                                 $from = $thissurvey['adminemail'];
                                 if (SendEmailMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) {
                                     $emailsent = "Y";
                                     $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), gT("An email has been sent with details about your saved survey"));
                                 }
                             }
                         }
                     } else {
                         safeDie("Unable to insert record into saved_control table.<br /><br />");
                     }
                 }
                 $aData['thisid'] = $last_db_id;
             }
             $aData['errormsg'] = $errormsg;
             $aData['dataentrymsgs'] = $aDataentrymsgs;
             $aData['sidemenu']['state'] = false;
             $this->_renderWrappedTemplate('dataentry', 'insert', $aData);
         }
     }
 }
开发者ID:CrandellWS,项目名称:LimeSurvey,代码行数:101,代码来源:dataentry.php


示例3: array

<?php

require_once "libreria.php";
$mode = "";
$titulo = "";
$producto = array("prdcod" => 0, "prddsc" => "", "ctgcod" => 0, "prdprc" => 0, "prdest" => "ACT", "prdstk" => 0);
if (isset($_POST["txtPrdCod"])) {
    $mode = $_GET["mode"];
    $producto = array("prdcod" => intval($_POST["txtPrdCod"]), "prddsc" => $_POST["txtPrdDsc"], "ctgcod" => intval($_POST["txtCtgCod"]), "prdprc" => floatval($_POST["txtPrdPrc"]), "prdest" => $_POST["cmbPrdEst"], "prdstk" => intval($_POST["txtPrdStk"]));
    //Aqui validar la data
    if ($mode == "INS") {
        insertarProducto($producto["prddsc"], $producto["ctgcod"], $producto["prdprc"], $producto["prdstk"], $producto["prdest"]);
        $_GET["mode"] = "UPD";
        $_GET["prdcod"] = getLastInsertID();
    }
    if ($mode == "UPD") {
        updateProducto($producto["prdcod"], $producto["prddsc"], $producto["ctgcod"], $producto["prdprc"], $producto["prdstk"], $producto["prdest"]);
    }
    if ($mode == "DEL") {
        deleteProducto($producto["prdcod"]);
        header("location:listadoProductos.php");
        die;
    }
}
if (isset($_GET["mode"])) {
    $mode = $_GET["mode"];
    switch ($mode) {
        case "INS":
            $titulo = "Nuevo Producto";
            break;
        case "UPD":
开发者ID:gujoalru,项目名称:IF412NegociosWeb,代码行数:31,代码来源:detalleProducto.php


示例4: ajaxSets

 public function ajaxSets()
 {
     $lid = Yii::app()->getRequest()->getPost('lid');
     $answers = Yii::app()->getRequest()->getPost('answers');
     $code = Yii::app()->getRequest()->getPost('code');
     $aAssessmentValues = Yii::app()->getRequest()->getPost('assessmentvalues', array());
     //Create new label set
     $language = "";
     foreach ($answers as $lang => $answer) {
         $language .= $lang . " ";
     }
     $language = trim($language);
     if ($lid == 0) {
         $lset = new LabelSet();
         $lset->label_name = Yii::app()->getRequest()->getPost('laname');
         $lset->languages = $language;
         $lset->save();
         $lid = getLastInsertID($lset->tableName());
     } else {
         Label::model()->deleteAll('lid = :lid', array(':lid' => $lid));
     }
     $res = 'ok';
     //optimistic
     foreach ($answers as $lang => $answer) {
         foreach ($answer as $key => $ans) {
             $label = new Label();
             $label->lid = $lid;
             $label->code = $code[$key];
             $label->title = $ans;
             $label->sortorder = $key;
             $label->language = $lang;
             $label->assessment_value = isset($aAssessmentValues[$key]) ? $aAssessmentValues[$key] : 0;
             if (!$label->save()) {
                 $res = 'fail';
             }
         }
     }
     echo ls_json_encode($res);
 }
开发者ID:wrenchpilot,项目名称:LimeSurvey,代码行数:39,代码来源:labels.php


示例5: XMLImportSurvey


//.........这里部分代码省略.........
    // TMSW Condition->Relevance:  Call  LEM->ConvertConditionsToRelevance
    // Import assessments --------------------------------------------------------
    if (isset($xml->assessments)) {
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            unset($insertdata['id']);
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[11]<br />");
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[12]<br />");
            $aQuotaReplacements[$oldid] = getLastInsertID('{{quota}}');
            $results['quota']++;
        }
    }
    // Import quota_members ------------------------------------------------------
    if (isset($xml->quota_members)) {
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $result = QuotaMember::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[13]<br />");
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings----------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
开发者ID:rouben,项目名称:LimeSurvey,代码行数:67,代码来源:import_helper.php


示例6: actionIndex


//.........这里部分代码省略.........
     }
     while ($mayinsert != true) {
         $newtoken = randomChars($tokenlength);
         $ntquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='{$newtoken}'";
         $usrow = Yii::app()->db->createCommand($ntquery)->queryRow();
         if (!$usrow) {
             $mayinsert = true;
         }
     }
     $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
     $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
     $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
     $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
     /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
       $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2')));   */
     // Insert new entry into tokens db
     Tokens_dynamic::sid($thissurvey['sid']);
     $token = new Tokens_dynamic();
     $token->firstname = $postfirstname;
     $token->lastname = $postlastname;
     $token->email = Yii::app()->request->getPost('register_email');
     $token->emailstatus = 'OK';
     $token->token = $newtoken;
     if ($starttime && $endtime) {
         $token->validfrom = $starttime;
         $token->validuntil = $endtime;
     }
     foreach ($attributeinsertdata as $k => $v) {
         $token->{$k} = $v;
     }
     $result = $token->save();
     /**
     $result = $connect->Execute($query, array($postfirstname,
     $postlastname,
     returnGlobal('register_email'),
     'OK',
     $newtoken)
     
     //                             $postattribute1,   $postattribute2)
     ) or safeDie ($query."<br />".$connect->ErrorMsg());  //Checked - According to adodb docs the bound variables are quoted automatically
     */
     $tid = getLastInsertID($token->tableName());
     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
     $fieldsarray["{FIRSTNAME}"] = $postfirstname;
     $fieldsarray["{LASTNAME}"] = $postlastname;
     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
     $message = $thissurvey['email_register'];
     $subject = $thissurvey['email_register_subj'];
     $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
     if (getEmailFormat($surveyid) == 'html') {
         $useHtmlEmail = true;
         $surveylink = $this->createAbsoluteUrl($surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $optoutlink = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $optinlink = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>";
         $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>";
         $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>";
     } else {
         $useHtmlEmail = false;
         $fieldsarray["{SURVEYURL}"] = $this->createAbsoluteUrl('' . $surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $fieldsarray["{OPTOUTURL}"] = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{OPTINURL}"] = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
     }
     $message = ReplaceFields($message, $fieldsarray);
     $subject = ReplaceFields($subject, $fieldsarray);
     $html = "";
     //Set variable
     $sitename = Yii::app()->getConfig('sitename');
     if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($surveyid))) {
         // TLR change to put date into sent
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $query = "UPDATE {{tokens_{$surveyid}}}\n" . "SET sent='{$today}' WHERE tid={$tid}";
         $result = dbExecuteAssoc($query) or show_error("Unable to execute this query : {$query}<br />");
         //Checked
         $html = "<center>" . $clang->gT("Thank you for registering to participate in this survey.") . "<br /><br />\n" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "<br /><br />\n" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})";
         $html = ReplaceFields($html, $fieldsarray);
         $html .= "<br /><br /></center>\n";
     } else {
         $html = "Email Error";
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['template']) {
         $thistpl = getTemplatePath(validateTemplateDir('default'));
     } else {
         $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
     }
     sendCacheHeaders();
     doHeader();
     Yii::app()->lang = $clang;
     // fetch the defined variables and pass it to the header footer templates.
     $redata = compact(array_keys(get_defined_vars()));
     $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
     $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
     echo $html;
     $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
     doFooter();
 }
开发者ID:ryu1inaba,项目名称:LimeSurvey,代码行数:101,代码来源:RegisterController.php


示例7: copyToCentral

 function copyToCentral($surveyid, $aAttributesToBeCreated, $aMapped, $overwriteauto = false, $overwriteman = false, $createautomap = true)
 {
     $tokenid = Yii::app()->session['participantid'];
     //List of token_id's to add to participants table
     $duplicate = 0;
     $sucessfull = 0;
     $writearray = array();
     $attid = array();
     //Will store the CPDB attribute_id of new or existing attributes keyed by CPDB at
     $pid = "";
     /* Grab all the existing attribute field names from the tokens table */
     $arr = Yii::app()->db->createCommand()->select('*')->from("{{tokens_{$surveyid}}}")->queryRow();
     if (is_array($arr)) {
         $tokenfieldnames = array_keys($arr);
         $tokenattributefieldnames = array_filter($tokenfieldnames, 'filterForAttributes');
     } else {
         $tokenattributefieldnames = array();
     }
     /* Create CPDB attributes */
     if (!empty($aAttributesToBeCreated)) {
         foreach ($aAttributesToBeCreated as $key => $value) {
             /* $key is the fieldname from the token table (ie "attribute_1")
              * $value is the 'friendly name' for the attribute (ie "Gender")
              */
             $insertnames = array('attribute_type' => 'TB', 'visible' => 'Y', 'defaultname' => $value);
             Yii::app()->db->createCommand()->insert('{{participant_attribute_names}}', $insertnames);
             $attid[$key] = $aAttributesToBeCreated[$key] = getLastInsertID('{{participant_attribute_names}}');
             /* eg $attid['attribute_1']='8372' */
             $insertnameslang = array('attribute_id' => $attid[$key], 'attribute_name' => urldecode($value), 'lang' => Yii::app()->session['adminlang']);
             Yii::app()->db->createCommand()->insert('{{participant_attribute_names_lang}}', $insertnameslang);
         }
     }
     /* Add the participants to the CPDB = Iterate through each $tokenid and create the new CPDB id*/
     foreach ($tokenid as $key => $tid) {
         if (is_numeric($tid) && $tid != "") {
             /* Get the data for this participant from the tokens table */
             $tobeinserted = Yii::app()->db->createCommand()->select('participant_id,firstname,lastname,email,language')->where('tid = :tid')->from('{{tokens_' . intval($surveyid) . '}}')->bindParam(":tid", $tid, PDO::PARAM_INT)->queryRow();
             /* See if there are any existing CPDB entries that match on firstname,lastname and email */
             $query = Yii::app()->db->createCommand()->select('*')->from('{{participants}}')->where('firstname = :firstname AND lastname = :lastname AND email = :email')->bindParam(":firstname", $tobeinserted['firstname'], PDO::PARAM_STR)->bindParam(":lastname", $tobeinserted['lastname'], PDO::PARAM_STR)->bindParam(":email", $tobeinserted['email'], PDO::PARAM_STR)->queryAll();
             /* If there is already an existing entry, add to the duplicate count */
             if (count($query) > 0) {
                 $duplicate++;
                 if ($overwriteman == "true" && !empty($aMapped)) {
                     foreach ($aMapped as $cpdbatt => $tatt) {
                         Participant::model()->updateAttributeValueToken($surveyid, $query[0]['participant_id'], $cpdbatt, $tatt);
                     }
                 }
             } else {
                 /* Create entry in participants table */
                 $black = !empty($tobeinserted['blacklisted']) ? $tobeinserted['blacklisted'] : 'N';
                 $pid = !empty($tobeinserted['participant_id']) ? $tobeinserted['participant_id'] : $this->gen_uuid();
                 $writearray = array('participant_id' => $pid, 'firstname' => $tobeinserted['firstname'], 'lastname' => $tobeinserted['lastname'], 'email' => $tobeinserted['email'], 'language' => $tobeinserted['language'], 'blacklisted' => $black, 'owner_uid' => Yii::app()->session['loginID'], 'created_by' => Yii::app()->session['loginID'], 'created' => date('Y-m-d H:i:s', time()));
                 Yii::app()->db->createCommand()->insert('{{participants}}', $writearray);
                 //Update token table and insert the new UUID
                 $data = array("participant_id" => $pid);
                 Yii::app()->db->createCommand()->update('{{tokens_' . intval($surveyid) . '}}', $data, "tid = {$tid}");
                 /* Now add any new attribute values */
                 if (!empty($aAttributesToBeCreated)) {
                     foreach ($aAttributesToBeCreated as $key => $value) {
                         Participant::model()->updateAttributeValueToken($surveyid, $pid, $attid[$key], $key);
                     }
                 }
                 /* Now add mapped attribute values */
                 if (!empty($aMapped)) {
                     foreach ($aMapped as $cpdbatt => $tatt) {
                         Participant::model()->updateAttributeValueToken($surveyid, $pid, $cpdbatt, $tatt);
                     }
                 }
                 $sucessfull++;
                 /* Create a survey_link */
                 $data = array('participant_id' => $pid, 'token_id' => $tid, 'survey_id' => $surveyid, 'date_created' => date('Y-m-d H:i:s', time()));
                 Yii::app()->db->createCommand()->insert('{{survey_links}}', $data);
             }
         }
     }
     if ($createautomap == "true") {
         $aAttributes = Survey::model()->findByPk($surveyid)->tokenattributes;
         if (!empty($aAttributesToBeCreated)) {
             // If automapping is enabled then update the token field properties with the mapped CPDB field ID
             foreach ($aAttributesToBeCreated as $tatt => $cpdbatt) {
                 $aAttributes[$tatt]['cpdbmap'] = $cpdbatt;
             }
             Yii::app()->db->createCommand()->update('{{surveys}}', array("attributedescriptions" => json_encode($aAttributes)), 'sid = ' . $surveyid);
         }
         if (!empty($aMapped)) {
             foreach ($aMapped as $cpdbatt => $tatt) {
                 // Update the attributedescriptions so future mapping can be done automatically
                 $aAttributes[$tatt]['cpdbmap'] = $cpdbatt;
             }
             Yii::app()->db->createCommand()->update('{{surveys}}', array("attributedescriptions" => json_encode($aAttributes)), 'sid = ' . $surveyid);
         }
     }
     $returndata = array('success' => $sucessfull, 'duplicate' => $duplicate, 'overwriteauto' => $overwriteauto, 'overwriteman' => $overwriteman);
     return $returndata;
 }
开发者ID:kochichi,项目名称:LimeSurvey,代码行数:95,代码来源:Participant.php


示例8: savedcontrol

 function savedcontrol()
 {
     //This data will be saved to the "saved_control" table with one row per response.
     // - a unique "saved_id" value (autoincremented)
     // - the "sid" for this survey
     // - the "srid" for the survey_x row id
     // - "saved_thisstep" which is the step the user is up to in this survey
     // - "saved_ip" which is the ip address of the submitter
     // - "saved_date" which is the date ofthe saved response
     // - an "identifier" which is like a username
     // - a "password"
     // - "fieldname" which is the fieldname of the saved response
     // - "value" which is the value of the response
     //We start by generating the first 5 values which are consistent for all rows.
     global $surveyid, $thissurvey, $errormsg, $publicurl, $sitename, $clang, $clienttoken, $thisstep;
     $timeadjust = getGlobalSetting('timeadjust');
     //Check that the required fields have been completed.
     $errormsg = '';
     if (empty($_POST['savename'])) {
         $errormsg .= $clang->gT("You must supply a name for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass'])) {
         $errormsg .= $clang->gT("You must supply a password for this saved session.") . "<br />\n";
     }
     if (empty($_POST['savepass']) || empty($_POST['savepass2']) || $_POST['savepass'] != $_POST['savepass2']) {
         $errormsg .= $clang->gT("Your passwords do not match.") . "<br />\n";
     }
     // if security question asnwer is incorrect
     if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
         if (empty($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) {
             $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     if (!empty($errormsg)) {
         return;
     }
     $duplicate = SavedControl::model()->findByAttributes(array('sid' => $surveyid, 'identifier' => $_POST['savename']));
     if (!empty($duplicate) && $duplicate->count() > 0) {
         $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n";
         return;
     } else {
         //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist
         if (!isset($_SESSION['survey_' . $surveyid]['srid'])) {
             $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
             $sdata = array("datestamp" => $today, "ipaddr" => getIPAddress(), "startlanguage" => $_SESSION['survey_' . $surveyid]['s_lang'], "refurl" => getenv("HTTP_REFERER"));
             if (SurveyDynamic::model($thissurvey['sid'])->insert($sdata)) {
                 $srid = getLastInsertID('{{survey_' . $surveyid . '}}');
                 $_SESSION['survey_' . $surveyid]['srid'] = $srid;
             } else {
                 safeDie("Unable to insert record into survey table.<br /><br />");
             }
         }
         //CREATE ENTRY INTO "saved_control"
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
         $saved_control = new SavedControl();
         $saved_control->sid = $surveyid;
         $saved_control->srid = $_SESSION['survey_' . $surveyid]['srid'];
         $saved_control->identifier = $_POST['savename'];
         // Binding does escape, so no quoting/escaping necessary
         $saved_control->access_code = md5($_POST['savepass']);
         $saved_control->email = $_POST['saveemail'];
         $saved_control->ip = getIPAddress();
         $saved_control->saved_thisstep = $thisstep;
         $saved_control->status = 'S';
         $saved_control->saved_date = $today;
         $saved_control->refurl = getenv('HTTP_REFERER');
         if ($saved_control->save()) {
             $scid = getLastInsertID('{{saved_control}}');
             $_SESSION['survey_' . $surveyid]['scid'] = $scid;
         } else {
             safeDie("Unable to insert record into saved_control table.<br /><br />");
         }
         $_SESSION['survey_' . $surveyid]['holdname'] = $_POST['savename'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         $_SESSION['survey_' . $surveyid]['holdpass'] = $_POST['savepass'];
         //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output
         //Email if needed
         if (isset($_POST['saveemail']) && validateEmailAddress($_POST['saveemail'])) {
             $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name'];
             $message = $clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
             $message .= "\n\n" . $thissurvey['name'] . "\n\n";
             $message .= $clang->gT("Name") . ": " . $_POST['savename'] . "\n";
             $message .= $clang->gT("Password") . ": " . $_POST['savepass'] . "\n\n";
             $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n";
             $message .= Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/{$scid}/loadname/" . rawurlencode($_POST['savename']) . "/loadpass/" . rawurlencode($_POST['savepass']) . "/lang/" . rawurlencode($clang->langcode));
             if ($clienttoken) {
                 $message .= "/token/" . rawurlencode($clienttoken);
             }
             $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
             if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid))) {
                 $emailsent = "Y";
             } else {
                 $errormsg .= $clang->gT('Error: Email failed, this may indicate a PHP Mail Setup problem on the server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.');
                 if (trim($thissurvey['adminemail']) == '') {
                     $errormsg .= $clang->gT('(Reason: Admin email address empty)');
                 }
             }
         }
         return $clang->gT('Your survey was successfully saved.');
     }
//.........这里部分代码省略.........
开发者ID:josetorerobueno,项目名称:test_repo,代码行数:101,代码来源:Save.php


示例9: storeAttributeCSV

 function storeAttributeCSV($data)
 {
     $insertnames = array('attribute_type' => $data['attribute_type'], 'visible' => $data['visible']);
     Yii::app()->db->createCommand()->insert('{{participant_attribute_names}}', $insertnames);
     $insertid = getLastInsertID($this->tableName());
     $insertnameslang = array('attribute_id' => $insertid, 'attribute_name' => $data['attribute_name'], 'lang' => Yii::app()->session['adminlang']);
     Yii::app()->db->createCommand()->insert('{{participant_attribute_names_lang}}', $insertnameslang);
     return $insertid;
 }
开发者ID:pmaonline,项目名称:limesurvey-quickstart,代码行数:9,代码来源:ParticipantAttributeNames.php


示例10: addGroup

 function addGroup($group_name, $group_description)
 {
     $iLoginID = intval(Yii::app()->session['loginID']);
     $iquery = "INSERT INTO {{user_groups}} (name, description, owner_id) VALUES(:group_name, :group_desc, :loginID)";
     $command = Yii::app()->db->createCommand($iquery)->bindParam(":group_name", $group_name, PDO::PARAM_STR)->bindParam(":group_desc", $group_description, PDO::PARAM_STR)->bindParam(":loginID", $iLoginID, PDO::PARAM_INT);
     $result = $command->query();
     if ($result) {
         //Checked
         $id = getLastInsertID($this->tableName());
         //Yii::app()->db->Insert_Id(db_table_name_nq('user_groups'),'ugid');
         if ($id > 0) {
             $user_in_groups_query = 'INSERT INTO {{user_in_groups}} (ugid, uid) VALUES (:ugid, :uid)';
             $command = Yii::app()->db->createCommand($user_in_groups_query)->bindParam(":ugid", $id, PDO::PARAM_INT)->bindParam(":uid", $iLoginID, PDO::PARAM_INT)->query();
         }
         return $id;
     } else {
         return -1;
     }
 }
开发者ID:pmaonline,项目名称:limesurvey-quickstart,代码行数:19,代码来源:User_groups.php


示例11: copyToCentral

 function copyToCentral($surveyid, $newarr, $mapped, $overwriteauto = false, $overwriteman = false, $createautomap = true)
 {
     $tokenid = Yii::app()->session['participantid'];
     //List of token_id's to add to participants table
     $duplicate = 0;
     $sucessfull = 0;
     $writearray = array();
     $attid = array();
     //Will store the CPDB attribute_id of new or existing attributes keyed by CPDB at
     $pid = "";
     /* Grab all the existing attribute field names from the tokens table */
     $arr = Yii::app()->db->createCommand()->select('*')->from("{{tokens_{$surveyid}}}")->queryRow();
     if (is_array($arr)) {
         $tokenfieldnames = array_keys($arr);
         $tokenattributefieldnames = array_filter($tokenfieldnames, 'filterForAttributes');
     } else {
         $tokenattributefieldnames = array();
     }
     /* Automatically mapped attribute names are named "attribute_cpdb_[some_number]" */
     foreach ($tokenattributefieldnames as $key => $value) {
         if ($value[10] == 'c') {
             $autoattid = substr($value, 15);
             $mapped[$autoattid] = $value;
         }
     }
     /* Create new CPDB attributes */
     if (!empty($newarr)) {
         foreach ($newarr as $key => $value) {
             /* $key is the fieldname from the token table (ie "attribute_1")
              * $value is the 'friendly name' for the attribute (ie "Gender")
              */
             $insertnames = array('attribute_type' => 'TB', 'visible' => 'Y');
             Yii::app()->db->createCommand()->insert('{{participant_attribute_names}}', $insertnames);
             $attid[$key] = getLastInsertID('{{participant_attribute_names}}');
             /* eg $attid['attribute_1']='8372' */
             $insertnameslang = array('attribute_id' => $attid[$key], 'attribute_name' => urldecode($value), 'lang' => Yii::app()->session['adminlang']);
             Yii::app()->db->createCommand()->insert('{{participant_attribute_names_lang}}', $insertnameslang);
         }
     }
     /* Add the participants to the CPDB = Iterate through each $tokenid and create the new CPDB id*/
     foreach ($tokenid as $key => $tid) {
         if (is_numeric($tid) && $tid != "") {
             /* Get the data for this participant from the tokens table */
             $tobeinserted = Yii::app()->db->createCommand()->select('participant_id,firstname,lastname,email,language')->where('tid = :tid')->from('{{tokens_' . intval($surveyid) . '}}')->bindParam(":tid", $tid, PDO::PARAM_INT)->queryRow();
             /* See if there are any existing CPDB entries that match on firstname,lastname and email */
             $query = Yii::app()->db->createCommand()->select('*')->from('{{participants}}')->where('firstname = :firstname AND lastname = :lastname AND email = :email')->bindParam(":firstname", $tobeinserted['firstname'], PDO::PARAM_STR)->bindParam(":lastname", $tobeinserted['lastname'], PDO::PARAM_STR)->bindParam(":email", $tobeinserted['email'], PDO::PARAM_STR)->queryAll();
             /* If there is already an existing entry, add to the duplicate count */
             if (count($query) > 0) {
                 $duplicate++;
                 //HERE is where we can add "overwrite" feature to update attribute values for existing participants
                 if ($overwriteauto == "true") {
                     if (!empty($newarr)) {
                         foreach ($newarr as $key => $value) {
                             Participants::model()->updateAttributeValueToken($surveyid, $query[0]['participant_id'], $attid[$key], $key);
                         }
                     }
                 }
                 if ($overwriteman == "true") {
                     /* Now add mapped attribute values */
                     if (!empty($mapped)) {
                         foreach ($mapped as $cpdbatt => $tatt) {
                             Participants::model()->updateAttributeValueToken($surveyid, $query[0]['participant_id'], $cpdbatt, $tatt);
                         }
                     }
                 }
             } else {
                 /* Create entry in participants table */
                 $black = !empty($tobeinserted['blacklisted']) ? $tobeinserted['blacklised'] : 'N';
                 $pid = !empty($tobeinserted['participant_id']) ? $tobeinserted['participant_id'] : $this->gen_uuid();
                 $writearray = array('participant_id' => $pid, 'firstname' => $tobeinserted['firstname'], 'lastname' => $tobeinserted['lastname'], 'email' => $tobeinserted['email'], 'language' => $tobeinserted['language'], 'blacklisted' => $black, 'owner_uid' => Yii::app()->session['loginID']);
                 Yii::app()->db->createCommand()->insert('{{participants}}', $writearray);
                 //Update token table and insert the new UUID
                 $data = array("participant_id" => $pid);
                 Yii::app()->db->createCommand()->update('{{tokens_' . intval($surveyid) . '}}', $data, "tid = {$tid}");
                 /* Now add any new attribute values */
                 if (!empty($newarr)) {
                     foreach ($newarr as $key => $value) {
                         Participants::model()->updateAttributeValueToken($surveyid, $pid, $attid[$key], $key);
                     }
                 }
                 /* Now add mapped attribute values */
                 if (!empty($mapped)) {
                     foreach ($mapped as $cpdbatt => $tatt) {
                         Participants::model()->updateAttributeValueToken($surveyid, $pid, $cpdbatt, $tatt);
                     }
                 }
                 $sucessfull++;
                 /* Create a survey_link */
                 $data = array('participant_id' => $pid, 'token_id' => $tid, 'survey_id' => $surveyid, 'date_created' => date('Y-m-d H:i:s', time()));
                 Yii::app()->db->createCommand()->insert('{{survey_links}}', $data);
             }
         }
     }
     if (!empty($newarr)) {
         /* Rename the token attribute fields to a cpdb field, so in future
          * we know that it belongs to a CPDB field */
         foreach ($newarr as $key => $value) {
             $newname = 'attribute_cpdb_' . intval($attid[$key]);
             $fields = array($value => array('name' => $newname, 'type' => 'TEXT'));
             //Rename the field in the tokens_[sid] table
//.........这里部分代码省略.........
开发者ID:ryu1inaba,项目名称:LimeSurvey,代码行数:101,代码来源:Participants.php



注:本文中的getLastInsertID函数示例整理自Git


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP getLastInsertId函数代码示例发布时间:2022-05-15
下一篇:
PHP getLastDate函数代码示例发布时间:2022-05-15
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap