当前位置: 首页>>代码示例>>PHP>>正文


PHP db_insert函数代码示例

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


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

示例1: addToUser

 public function addToUser($postData, $user_id)
 {
     // $postData['news_date'] = date("Y-m-d H:i:s");
     $postData['author'] = 1;
     // echo "<pre>";var_dump($postData);echo (db_insert($this->table, $postData));die;
     return db_insert($this->table, $postData);
 }
开发者ID:softwareEngineer4444,项目名称:khuyennong,代码行数:7,代码来源:question.php

示例2: insertAgreement

 /**
  * The student inserts this initially once he/she accepts a project offer
  * @param unknown $props
  * @param unknown $proposal_id
  * @return boolean|unknown
  */
 static function insertAgreement($props)
 {
     if (!$props) {
         drupal_set_message(t('Insert requested with empty (filtered) data set'), 'error');
         return false;
     }
     if (!isset($props['proposal_id'])) {
         drupal_set_message(t('Insert requested with no proposal set'), 'error');
         return false;
     }
     global $user;
     $txn = db_transaction();
     try {
         $proposal = objectToArray(Proposal::getInstance()->getProposalById($props['proposal_id']));
         $project = objectToArray(Project::getProjectById($proposal['pid']));
         if (!isset($props['student_id'])) {
             $props['student_id'] = $user->uid;
         }
         if (!isset($props['supervisor_id'])) {
             $props['supervisor_id'] = $proposal['supervisor_id'];
         }
         if (!isset($props['mentor_id'])) {
             $props['mentor_id'] = $project['mentor_id'];
         }
         $props['project_id'] = $proposal['pid'];
         if (!isset($props['description'])) {
             $props['description'] = '';
         }
         if (!isset($props['student_signed'])) {
             $props['student_signed'] = 0;
         }
         if (!isset($props['supervisor_signed'])) {
             $props['supervisor_signed'] = 0;
         }
         if (!isset($props['mentor_signed'])) {
             $props['mentor_signed'] = 0;
         }
         /*
         if (! testInput($props, array('owner_id', 'org_id', 'inst_id', 'supervisor_id','pid', 'title'))){
         	return FALSE;
         }
         */
         try {
             $id = db_insert(tableName(_AGREEMENT_OBJ))->fields($props)->execute();
         } catch (Exception $e) {
             drupal_set_message($e->getMessage(), 'error');
         }
         if ($id) {
             drupal_set_message(t('You have created your agreement: you can continue editing it later.'));
             return $id;
         } else {
             drupal_set_message(t('We could not add your agreement. ') . (_DEBUG ? '<br/>' . getDrupalMessages() : ""), 'error');
         }
         return $result;
     } catch (Exception $ex) {
         $txn->rollback();
         drupal_set_message(t('We could not add your agreement.') . (_DEBUG ? $ex->__toString() : ''), 'error');
     }
     return FALSE;
 }
开发者ID:edwinraycom,项目名称:vals-soc,代码行数:66,代码来源:Agreement.php

示例3: testInsertDuplicateData

 /**
  * Tests aborting of traditional SQL database systems with invalid data.
  */
 function testInsertDuplicateData()
 {
     // Try to insert multiple records where at least one has bad data.
     try {
         db_insert('test')->fields(array('name', 'age', 'job'))->values(array('name' => 'Elvis', 'age' => 63, 'job' => 'Singer'))->values(array('name' => 'John', 'age' => 17, 'job' => 'Consultant'))->values(array('name' => 'Frank', 'age' => 75, 'job' => 'Singer'))->execute();
         $this->fail('Insert succeedded when it should not have.');
     } catch (IntegrityConstraintViolationException $e) {
         // Check if the first record was inserted.
         $name = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 63))->fetchField();
         if ($name == 'Elvis') {
             if (!Database::getConnection()->supportsTransactions()) {
                 // This is an expected fail.
                 // Database engines that don't support transactions can leave partial
                 // inserts in place when an error occurs. This is the case for MySQL
                 // when running on a MyISAM table.
                 $this->pass("The whole transaction has not been rolled-back when a duplicate key insert occurs, this is expected because the database doesn't support transactions");
             } else {
                 $this->fail('The whole transaction is rolled back when a duplicate key insert occurs.');
             }
         } else {
             $this->pass('The whole transaction is rolled back when a duplicate key insert occurs.');
         }
         // Ensure the other values were not inserted.
         $record = db_select('test')->fields('test', array('name', 'age'))->condition('age', array(17, 75), 'IN')->execute()->fetchObject();
         $this->assertFalse($record, 'The rest of the insert aborted as expected.');
     }
 }
开发者ID:davidsoloman,项目名称:drupalconsole.com,代码行数:30,代码来源:InvalidDataTest.php

示例4: submitForm

 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     //TODO v2 Send Email via Cron not on Submit
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $username = $user->get('name')->value;
     $userId = $user->get('uid')->value;
     $mailManager = \Drupal::service('plugin.manager.mail');
     $jobNode = \Drupal::routeMatch()->getParameter('node');
     $jobNodeTitle = $jobNode->getTitle();
     $companyNodeEntity = $jobNode->get('field_company');
     $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
     $companyEmail = $companyNode->field_email->value;
     $resumeFileId = $form_state->getValue('resume');
     $resumeFile = db_select('file_managed', 'f')->condition('f.fid', $resumeFileId, '=')->fields('f', array('uri'))->execute()->fetchField();
     $atttachment = array('filepath' => $resumeFile);
     $module = 'job_mailer';
     $key = 'apply_job';
     $params['job_title'] = $jobNodeTitle;
     $params['message'] = "<html>\n           <p>Please see attached resume for user: {$username}\n           </html>";
     $params['attachment'] = $atttachment;
     $langcode = \Drupal::currentUser()->getPreferredLangcode();
     $send = true;
     $reply = \Drupal::config('system.site')->get('mail');
     $result = $mailManager->mail($module, $key, $companyEmail, $langcode, $params, $reply, $send);
     db_insert('user_job_application')->fields(array('job_id' => $jobNode->id(), 'user_id' => $userId, 'date' => date('Y-m-d H:i:s')))->execute();
     drupal_set_message('Your application has been sent.');
 }
开发者ID:augustpascual-mse,项目名称:job-searching-network,代码行数:30,代码来源:ApplyForm.php

示例5: add_tag

 public function add_tag($idPost, $tag)
 {
     $idTag = NULL;
     $arrTag = explode(",", $tag);
     foreach ($arrTag as $t) {
         $t = trim($t);
         //bo cac khoang trang
         if ($t != "") {
             //truong hop k co tag
             //query tag table
             $sql = "SELECT * FROM `{$this->table_tag}` where `name` = '{$t}'";
             $result = db_get_all($sql);
             if (count($result) == 0) {
                 $temp = array('name' => $t);
                 db_insert($this->table_tag, $temp);
                 $idTag = mysql_insert_id();
             } else {
                 //lay id cua tag nay
                 $idTag = $result[0]['id'];
             }
             $temp2 = array('post_id' => $idPost, 'tag_id' => $idTag);
             db_insert('post_tag', $temp2);
         }
     }
 }
开发者ID:quyen91,项目名称:simple-mvc,代码行数:25,代码来源:news.php

示例6: api_graph_template_suggested_values_save

function api_graph_template_suggested_values_save($graph_template_id, $_fields_suggested_values) {
	require_once(CACTI_BASE_PATH . "/lib/sys/sequence.php");

	/* sanity checks */
	validate_id_die($graph_template_id, "graph_template_id");

	/* insert the new custom field values */
	if (is_array($_fields_suggested_values) > 0) {
		foreach ($_fields_suggested_values as $field_name => $field_array) {
			foreach ($field_array as $field_item) {
				if (empty($field_item["id"])) {
					db_insert("graph_template_suggested_value",
						array(
							"id" => array("type" => DB_TYPE_INTEGER, "value" => "0"),
							"graph_template_id" => array("type" => DB_TYPE_INTEGER, "value" => $graph_template_id),
							"field_name" => array("type" => DB_TYPE_STRING, "value" => $field_name),
							"value" => array("type" => DB_TYPE_STRING, "value" => $field_item["value"]),
							"sequence" => array("type" => DB_TYPE_INTEGER, "value" => seq_get_current(0, "sequence", "graph_template_suggested_value", "graph_template_id = " . sql_sanitize($graph_template_id) . " and field_name = '" . sql_sanitize($field_name) . "'"))
							),
						array("id"));
				}else{
					db_update("graph_template_suggested_value",
						array(
							"id" => array("type" => DB_TYPE_INTEGER, "value" => $field_item["id"]),
							"value" => array("type" => DB_TYPE_STRING, "value" => $field_item["value"])
							),
						array("id"));
				}
			}
		}
	}
}
开发者ID:songchin,项目名称:Cacti,代码行数:32,代码来源:graph_template_update.php

示例7: apachesolr_mark_node

 function apachesolr_mark_node($nid)
 {
     if (function_exists('apachesolr_mark_entity')) {
         // Bug killer - Check if the target nodeId exists in the apachesolr_index_entities_node table...
         $nodeExistsInIndexTbl = false;
         $query = "SELECT count(entity_id) AS 'count' FROM apachesolr_index_entities_node WHERE entity_id={$nid} ";
         $results = db_query($query);
         foreach ($results as $record) {
             if (intval($record->count) > 0) {
                 $nodeExistsInIndexTbl = true;
             }
             break;
         }
         // Bug killer - If the target nodeId does not exist in the apachesolr_index_entities_node table, insert it
         if ($nodeExistsInIndexTbl === false) {
             $results = db_query("SELECT nid, type, status, changed FROM node WHERE nid={$nid} LIMIT 1");
             foreach ($results as $record) {
                 $nodeInfo = $record;
             }
             if (!empty($nodeInfo)) {
                 db_insert('apachesolr_index_entities_node')->fields(array('entity_type' => 'node', 'entity_id' => $nid, 'bundle' => $nodeInfo->type, 'status' => $nodeInfo->status, 'changed' => $nodeInfo->changed))->execute();
             }
         }
         apachesolr_mark_entity('node', $nid);
     }
 }
开发者ID:hosttor,项目名称:BusinessUSA-OpenSource,代码行数:26,代码来源:Solr-BackwardsCompatability-SpachesolrMarkNode.php

示例8: hook_node_convert_change

/**
 * This is an example implementation for the hook. Preforms actions when converting a node based on it's type.
 *
 * @param $data
 *   An array containing information about the conversion process. The keys are
 *   - dest_node_type  The destination type of the node
 *   - node  The node object
 *   - Any other information passed by $op = 'options' or $op = 'options validate'
 * @param $op
 *   A string containing the operation which should be executed. These are the possible values
 *   - insert  Operations which should be run when the node is transferred to the new node type.
 *   Usually for transferring and adding new node information into the database.
 *   - delete  Operations which should be run after the node is transferred to the new node type.
 *   Usually for deleting unneeded information from the database after the transfer.
 *   - options  Configuration elements shown on the conversion form. Should return a FAPI array.
 *   - options validate  Validation check on the options elements.
 * @return
 *    Should return a FAPI array only when using the options operation.
 */
function hook_node_convert_change($data, $op)
{
    // All of this is just an example.
    if ($op == 'insert') {
        if ($data['dest_node_type'] == 'book') {
            $book = array();
            $node = $data['node'];
            $book['link_path'] = 'node/' . $node->nid;
            $book['link_title'] = $node->title;
            $book['plid'] = 0;
            $book['menu_name'] = book_menu_name($node->nid);
            $mlid = menu_link_save($book);
            $book['bid'] = $data['hook_options']['bid'];
            if ($book['bid'] == 'self') {
                $book['bid'] = $node->nid;
            }
            $id = db_insert('book')->fields(array('nid' => $node->nid, 'mlid' => $book['mlid'], 'bid' => $book['bid']))->execute();
        }
        if ($data['dest_node_type'] == 'forum') {
            $id = db_insert('forum')->fields(array('tid' => $data['hook_options']['forum'], 'vid' => $data['node']->vid, 'nid' => $data['node']->nid))->execute();
            $id = db_insert('taxonomy_term_node')->fields(array('tid' => $data['hook_options']['forum'], 'vid' => $data['node']->vid, 'nid' => $data['node']->nid))->execute();
        }
    } elseif ($op == 'delete') {
        if ($data['node']->type == 'book') {
            menu_link_delete($data['node']->book['mlid']);
            db_delete('book')->condition('mlid', $data['node']->book['mlid'])->execute();
        }
        if ($data['node']->type == 'forum') {
            db_delete('forum')->condition('nid', $data['node']->nid)->execute();
            db_delete('taxonomy_term_node')->condition('nid', $data['node']->nid)->execute();
        }
    } elseif ($op == 'options') {
        $form = array();
        if ($data['dest_node_type'] == 'book') {
            foreach (book_get_books() as $book) {
                $options[$book['nid']] = $book['title'];
            }
            $options = array('self' => '<' . t('create a new book') . '>') + $options;
            $form['bid'] = array('#type' => 'select', '#title' => t('Book'), '#options' => $options, '#description' => t('Your page will be a part of the selected book.'), '#attributes' => array('class' => 'book-title-select'));
        }
        if ($data['dest_node_type'] == 'forum') {
            $vid = variable_get('forum_nav_vocabulary', '');
            $form['forum'] = taxonomy_form($vid);
            $form['forum']['#weight'] = 7;
            $form['forum']['#required'] = TRUE;
            $form['forum']['#options'][''] = t('- Please choose -');
        }
        return $form;
    } elseif ($op == 'options validate') {
        $form_state = $data['form_state'];
        if ($data['dest_node_type'] == 'forum') {
            $containers = variable_get('forum_containers', array());
            $term = $form_state['values']['hook_options']['forum'];
            if (in_array($term, $containers)) {
                $term = taxonomy_term_load($term);
                form_set_error('hook_options][forum', t('The item %forum is only a container for forums. Please select one of the forums below it.', array('%forum' => $term->name)));
            }
        }
    }
}
开发者ID:ehazell,项目名称:AWBA,代码行数:79,代码来源:node_convert.api.php

示例9: updateDatabase

 /**
  * Write the values into the database.
  * Return 0 if there was an error, else 1.
  */
 function updateDatabase($form, $myvalues)
 {
     //Try to create the record now
     $nSiteID = $this->m_oContext->getSiteID();
     $nIEN = $myvalues['tid'];
     $nUID = $this->m_oContext->getUID();
     $sCWFS = $this->m_oTT->getTicketWorkflowState($nSiteID . '-' . $nIEN);
     $updated_dt = date("Y-m-d H:i:s", time());
     if ($myvalues['reason'] == 'Other' && (!isset($myvalues['suspend_notes_tx']) || trim($myvalues['suspend_notes_tx']) == '')) {
         form_set_error('suspend_notes_tx', 'Cannot suspend a ticket without an explanation when reason is "Other".');
         return 0;
     }
     //Create the raptor_ticket_suspend_notes record now
     try {
         $oInsert = db_insert('raptor_ticket_suspend_notes')->fields(array('siteid' => $nSiteID, 'IEN' => $nIEN, 'notes_tx' => 'REASON:' . $myvalues['reason'] . '<br>NOTES:' . $myvalues['suspend_notes_tx'], 'author_uid' => $nUID, 'created_dt' => $updated_dt))->execute();
     } catch (\Exception $e) {
         error_log('Failed to create raptor_ticket_suspend_notes: ' . $e . "\nDetails..." . print_r($oInsert, true));
         form_set_error('suspend_notes_tx', 'Failed to save notes for this ticket!');
         return 0;
     }
     $sNewWFS = 'IA';
     $this->m_oTT->setTicketWorkflowState($nSiteID . '-' . $nIEN, $nUID, $sNewWFS, $sCWFS, $updated_dt);
     //Write success message
     drupal_set_message('Suspended ' . $myvalues['tid'] . ' (' . $myvalues['procName'] . ')');
     return 1;
 }
开发者ID:rmurray1,项目名称:RAPTOR,代码行数:30,代码来源:SuspendTicketPage.php

示例10: addToUser

 public function addToUser($postData, $user_id)
 {
     $postData['datetime'] = date("Y-m-d H:i:s");
     $postData['user_id'] = $user_id;
     // var_dump($postData);die();
     return db_insert($this->table, $postData);
 }
开发者ID:herotran-nguyenanh,项目名称:webdevelopver,代码行数:7,代码来源:post.php

示例11: storemore

 /**
  * called by $this->store() after storing $this->values in the database
  * can be used to update additional tables, call scripts etc.
  */
 protected function storemore()
 {
     if ($this->new && $this->values['default_aliases']) {
         foreach (Config::read('default_aliases') as $address => $goto) {
             $address = $address . "@" . $this->id;
             # if $goto doesn't contain @, let the alias point to the same domain
             if (!strstr($goto, '@')) {
                 $goto = $goto . "@" . $this->id;
             }
             # TODO: use AliasHandler->add instead of writing directly to the alias table
             $arr = array('address' => $address, 'goto' => $goto, 'domain' => $this->id);
             $result = db_insert('alias', $arr);
             # TODO: error checking
         }
     }
     if ($this->new) {
         if (!$this->domain_postcreation()) {
             $this->errormsg[] = Config::lang('domain_postcreate_failed');
         }
     } else {
         # we don't have domain_postedit()
     }
     return true;
     # TODO: don't hardcode
 }
开发者ID:mpietruschka,项目名称:postfixadmin,代码行数:29,代码来源:DomainHandler.php

示例12: addComment

 function addComment($props)
 {
     if (!$props) {
         drupal_set_message(t('Insert requested with empty (filtered) data set'), 'error');
         return false;
     }
     //global $user;
     $txn = db_transaction();
     try {
         //$uid = $user->uid;
         //$props['author'] = $uid;
         $now = new DateTime();
         $props['date_posted'] = $now->format('Y-m-d H:i:s');
         // check for top level posts with an empty parent & set it to mysql null.
         if (!isset($props['parent_id']) || empty($props['parent_id'])) {
             $props['parent_id'] = null;
         }
         $result = FALSE;
         $query = db_insert(tableName('comment'))->fields($props);
         $id = $query->execute();
         if ($id) {
             $result = $id;
         } else {
             drupal_set_message(t('We could not add your comment'), 'error');
         }
     } catch (Exception $ex) {
         $txn->rollback();
         drupal_set_message(t('We could not add your comment. ') . (_DEBUG ? $ex->__toString() : ''), 'error');
     }
     return $result;
 }
开发者ID:edwinraycom,项目名称:vals-soc,代码行数:31,代码来源:ThreadedComments.php

示例13: createInvoice

 public function createInvoice($user_id = NULL)
 {
     $response = array();
     if (isset($user_id) && $user_id > 0) {
         $user_storage = \Drupal::entityManager()->getStorage('user');
         $user = $user_storage->load($user_id);
         $total_price = 0;
         $total_quantity = 0;
         if (isset($user)) {
             // insert new invoice
             $fields = array('user_id' => $user_id, 'total_quantity' => 0, 'total_price' => 0, 'date' => time(), 'note' => '');
             $invoice_id = db_insert('invoice')->fields($fields)->execute();
             // create relationship between invoice and purchased products of customer
             $fields = array('invoice_id' => $invoice_id);
             db_update('product_user_relationship')->condition('user_id', $user_id)->condition('status', 1)->isNull('invoice_id')->fields($fields)->execute();
             // update total_price and total_quantity
             $rows = db_select('product_user_relationship', 'e')->condition('invoice_id', $invoice_id)->fields('e', array('total_price', ' quantity'))->execute()->fetchAll();
             foreach ($rows as $row) {
                 $total_price += $row->total_price;
                 $total_quantity += $row->quantity;
             }
             // re-update invoice: total price, total quantity
             $fields = array('total_price' => $total_price, 'total_quantity' => $total_quantity);
             db_update('invoice')->condition('id', $invoice_id)->fields($fields)->execute();
             $response = array('success' => true, 'message' => $this->t('Create successfully.'));
         }
     }
     return new JsonResponse($response);
 }
开发者ID:namquy,项目名称:websitegomsu,代码行数:29,代码来源:InvoiceController.php

示例14: insert_profiles

/**
 * プロフィールの登録
 *
 * @param array $queries
 * @param array $options
 *
 * @return resource
 */
function insert_profiles($queries, $options = array())
{
    $queries = db_placeholder($queries);
    // 初期値を取得
    $defaults = default_profiles();
    if (isset($queries['values']['created'])) {
        if ($queries['values']['created'] === false) {
            unset($queries['values']['created']);
        }
    } else {
        $queries['values']['created'] = $defaults['created'];
    }
    if (isset($queries['values']['modified'])) {
        if ($queries['values']['modified'] === false) {
            unset($queries['values']['modified']);
        }
    } else {
        $queries['values']['modified'] = $defaults['modified'];
    }
    // データを登録
    $queries['insert_into'] = DATABASE_PREFIX . 'profiles';
    $resource = db_insert($queries);
    if (!$resource) {
        return $resource;
    }
    return $resource;
}
开发者ID:refirio,项目名称:levis-members,代码行数:35,代码来源:profiles.php

示例15: _tranCrear

function _tranCrear($oid)
{
    $data = array("id_orden" => $oid);
    $query = db_insert("todopago_transaccion");
    $query->fields($data)->execute();
    return _tranEstado($oid);
}
开发者ID:TodoPago,项目名称:Plugin-Drupal-Commerce,代码行数:7,代码来源:commerce_todo_pago_general.php


注:本文中的db_insert函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。