The following directives can be used in the query format string:
%d (integer)
%f (float)
%s (string)
%% (literal percentage sign - no argument needed)
All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
Literals (%) as parts of the query must be properly written as %%.
This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
Does not support sign, padding, alignment, width or precision specifiers.
Does not support argument numbering/swapping.
May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
Both %d and %s should be left unquoted in the query string.
wpdb::prepare( "SELECT * FROM table WHERE column = %s AND field = %d", 'foo', 1337 )
wpdb::prepare( "SELECT DATE_FORMAT(field, '%%c') FROM table WHERE column = %s", 'foo' );
public prepare ( string $query, array | mixed $args ) : null | false | string | ||
$query | string | Query statement with sprintf()-like placeholders |
$args | array | mixed | The array of variables to substitute into the query's placeholders if being called like {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if being called like {@link http://php.net/sprintf sprintf()}. |
return | null | false | string | Sanitized query string, null if there is no query, false if there is an error and string if there was something to prepare |
public function query($query, $parameters = array()) { if (!empty($parameters)) { $query = str_replace('?', '%s', $query); $query = $this->wpdb->prepare($query, $parameters); } return $this->wpdb->query($query); }
public function launchkey_cron() { $table_name = $this->wpdb->prefix . 'launchkey_sso_sessions'; $dt = new DateTime("- 1 hour"); $dt->setTimezone(new DateTimeZone("UTC")); $this->wpdb->query($this->wpdb->prepare("DELETE FROM {$table_name} WHERE seen < %s", $dt->format("Y-m-d H:i:s"))); }
/** * * Given the sql array and the search manager, this method will update the query * * @param AbstractSearch $searchManager * @param array $sql * @param \wpdb $databaseAdapter * @return array * @author Tim Perry */ public function updateQuery(AbstractSearch $searchManager, array $sql, \wpdb $databaseAdapter) { if (!$searchManager->queryVarExists(self::QUERY_VAR_KEYWORDS)) { return $sql; } $keywords = $searchManager->getQueryVar(self::QUERY_VAR_KEYWORDS); if (empty($keywords)) { return $sql; } if ($keywordsArray = explode(" ", $keywords)) { $sql["select"] .= ", "; $sql["where"] .= " and ( "; foreach ($keywordsArray as $keyword) { $sql["select"] .= $databaseAdapter->prepare("case when p.post_title like '%%%s%%' then 5 else 0 end + ", $keyword); $sql["select"] .= $databaseAdapter->prepare("case when p.post_content like '%%%s%%' then 1 else 0 end + ", $keyword); $sql["where"] .= $databaseAdapter->prepare("p.post_title like '%%%s%%' or ", $keyword); $sql["where"] .= $databaseAdapter->prepare("p.post_content like '%%%s%%' or ", $keyword); } $sql["where"] = rtrim($sql["where"], "or "); $sql["where"] .= ") "; $sql["select"] = rtrim($sql["select"], "+ "); $sql["select"] .= " as matches"; $sql["orderby"] = "order by matches desc, post_date desc"; } return $sql; }
public function getResults($query, $parameters = array()) { if (!empty($parameters)) { $query = str_replace('?', '%s', $query); $query = $this->wpdb->prepare($query, $parameters); } return $this->wpdb->get_results($query, ARRAY_A); }
/** * Deletes all plugin terms. * * @return void */ private function delete_terms() { $query = "\nSELECT term_id\nFROM {$this->wpdb->term_taxonomy}\nWHERE taxonomy = %s\nLIMIT 500"; $query = $this->wpdb->prepare($query, $this->taxonomy); while ($term_ids = $this->wpdb->get_col($query)) { foreach ($term_ids as $term_id) { wp_delete_term($term_id, $this->taxonomy); } } }
/** * Deletes all remote MultilingualPress nav menu items linking to the (to-be-deleted) site with the given ID. * * @param int $deleted_site_id The ID of the to-be-deleted site. * * @return void */ public function delete_items_for_deleted_site($deleted_site_id) { $query = "\nSELECT blog_id\nFROM {$this->wpdb->blogs}\nWHERE blog_id != %d"; $query = $this->wpdb->prepare($query, $deleted_site_id); foreach ($this->wpdb->get_col($query) as $site_id) { switch_to_blog($site_id); $query = "\nSELECT p.ID\nFROM {$this->wpdb->posts} p\nINNER JOIN {$this->wpdb->postmeta} pm\nON p.ID = pm.post_id\nWHERE pm.meta_key = %s\n\tAND pm.meta_value = %s"; $query = $this->wpdb->prepare($query, $this->meta_key, $deleted_site_id); foreach ($this->wpdb->get_col($query) as $post_id) { wp_delete_post($post_id, true); } restore_current_blog(); } }
function global_site_search_page_setup() { $page_id = get_option('global_site_search_page', false); if (empty($page_id) || !is_object(get_post($page_id)) && is_super_admin()) { // a page hasn't been set - so check if there is already one with the base name $page_id = $this->db->get_var($this->db->prepare("SELECT ID FROM {$this->db->posts} WHERE post_name = %s AND post_type = 'page'", $this->global_site_search_base)); if (empty($page_id)) { // Doesn't exist so create the page $page_id = wp_insert_post(array("post_content" => '', "post_title" => __('Site Search', 'globalsitesearch'), "post_excerpt" => '', "post_status" => 'publish', "comment_status" => 'closed', "ping_status" => 'closed', "post_name" => $this->global_site_search_base, "post_type" => 'page')); flush_rewrite_rules(); } update_option('global_site_search_page', $page_id); } }
/** * @param string $query * @param array $args * @param int $elements_num * * @return array */ public function retrieve($query, $args, $elements_num) { $result = array(); $offset = 0; while ($offset < $elements_num) { $new_query = $query . sprintf(' LIMIT %d OFFSET %s', $this->chunk_size, $offset); $new_query = $this->wpdb->prepare($new_query, $args); $rowset = $this->wpdb->get_results($new_query, ARRAY_A); if (is_array($rowset) && count($rowset)) { $result = array_merge($result, $rowset); } $offset += $this->chunk_size; } return $result; }
/** * @param string $cms_id * @param bool|TranslationProxy_Service $translation_service * * @return int|null translation id for the given cms_id's target */ public function get_translation_id($cms_id, $translation_service = false) { list($post_type, $element_id, , $target_lang) = $this->parse_cms_id($cms_id); $translation = $this->wpdb->get_row($this->wpdb->prepare("\n\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT t.translation_id, j.job_id, t.element_id\n\t\t\t\t\t\t\t\t\t\t\t\t\tFROM {$this->wpdb->prefix}icl_translations t\n\t\t\t\t\t\t\t\t\t\t\t\t\tJOIN {$this->wpdb->prefix}icl_translations o\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tON o.trid = t.trid\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND o.element_type = t.element_type\n\t\t\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN {$this->wpdb->prefix}icl_translation_status st\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tON st.translation_id = t.translation_id\n\t\t\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN {$this->wpdb->prefix}icl_translate_job j\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tON j.rid = st.rid\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE o.element_id=%d\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND t.language_code=%s\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND o.element_type LIKE %s\n\t\t\t\t\t\t\t\t\t\t\t\t\tLIMIT 1", $element_id, $target_lang, '%_' . $post_type)); $translation_id = $this->maybe_cleanup_broken_row($translation, $translation_service); if ($translation_service && !isset($translation_id) && $translation_service) { $job_id = $this->job_factory->create_local_post_job($element_id, $target_lang); $job = $this->job_factory->get_translation_job($job_id, false, false, true); $translation_id = $job ? $job->get_translation_id() : 0; if ($translation_id) { $this->tm_records->icl_translation_status_by_translation_id($translation_id)->update(array('status' => ICL_TM_IN_PROGRESS, 'translation_service' => $translation_service->id)); } } return $translation_id; }
private function persist() { foreach (array_chunk($this->data, self::INSERT_CHUNK_SIZE) as $chunk) { $query = "INSERT IGNORE INTO {$this->wpdb->prefix}icl_strings " . '(`language`, `context`, `gettext_context`, `domain_name_context_md5`, `name`, `value`, `status`) VALUES '; $i = 0; foreach ($chunk as $string) { if ($i > 0) { $query .= ','; } $query .= $this->wpdb->prepare("('%s', '%s', '%s', '%s', '%s', '%s', %d)", $this->get_source_lang($string['name'], $string['domain']), $string['domain'], $string['gettext_context'], md5($string['domain'] . $string['name'] . $string['gettext_context']), $string['name'], $string['value'], ICL_TM_NOT_TRANSLATED); $i++; } $this->wpdb->query($query); } }
/** * @param int $limit * @return mixed */ public function getTopFailedLogins($limit = 10) { $interval = 'UNIX_TIMESTAMP(DATE_SUB(NOW(), interval 7 day))'; switch (wfConfig::get('email_summary_interval', 'weekly')) { case 'daily': $interval = 'UNIX_TIMESTAMP(DATE_SUB(NOW(), interval 1 day))'; break; case 'monthly': $interval = 'UNIX_TIMESTAMP(DATE_SUB(NOW(), interval 1 month))'; break; } $failedLogins = $this->db->get_results($this->db->prepare(<<<SQL SELECT wfl.*, sum(wfl.fail) as fail_count FROM {$this->db->base_prefix}wfLogins wfl WHERE wfl.fail = 1 AND wfl.ctime > {$interval} GROUP BY wfl.username ORDER BY fail_count DESC LIMIT %d SQL , $limit)); foreach ($failedLogins as &$login) { $exists = $this->db->get_var($this->db->prepare(<<<SQL SELECT !ISNULL(ID) FROM {$this->db->base_prefix}users WHERE user_login = '******' OR user_email = '%s' SQL , $login->username, $login->username)); $login->is_valid_user = $exists; } return $failedLogins; }
/** * Retrieve array of URLs that pingbacked the given URL. * * Specs on http://www.aquarionics.com/misc/archives/blogite/0198.html * * @since 1.5.0 * * @param string $url * @return array|IXR_Error */ public function pingback_extensions_getPingbacks($url) { /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */ do_action('xmlrpc_call', 'pingback.extensions.getPingbacks'); $url = $this->escape($url); $post_ID = url_to_postid($url); if (!$post_ID) { // We aren't sure that the resource is available and/or pingback enabled return $this->pingback_error(33, __('The specified target URL cannot be used as a target. It either doesn’t exist, or it is not a pingback-enabled resource.')); } $actual_post = get_post($post_ID, ARRAY_A); if (!$actual_post) { // No such post = resource not found return $this->pingback_error(32, __('The specified target URL does not exist.')); } $comments = $this->db->get_results($this->db->prepare("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM {$this->db->comments} WHERE comment_post_ID = %d", $post_ID)); if (!$comments) { return array(); } $pingbacks = array(); foreach ($comments as $comment) { if ('pingback' == $comment->comment_type) { $pingbacks[] = $comment->comment_author_url; } } return $pingbacks; }
/** * @param $source_site_id * @param $target_site_id * @param $source_content_id * @param $target_content_id * @param $type * @return mixed */ private function get_existing_translation_ids($source_site_id, $target_site_id, $source_content_id, $target_content_id, $type) { $sql = "\n\t\t\tSELECT DISTINCT `ml_source_blogid`, `ml_source_elementid`\n\t\t\tFROM {$this->link_table}\n\t\t\tWHERE (\n\t\t\t\t ( `ml_blogid` = %d AND `ml_elementid` = %d )\n\t\t\t\tOR ( `ml_blogid` = %d AND `ml_elementid` = %d )\n\t\t\t\t)\n\t\t\t\tAND `ml_type` = %s"; $query = $this->wpdb->prepare($sql, $source_site_id, $source_content_id, $target_site_id, $target_content_id, $type); $result = $this->wpdb->get_results($query, ARRAY_A); return $result; }
private function select_translation_id($where, $prepare_args) { $this->translation_id = $this->wpdb->get_var("SELECT translation_id FROM {$this->wpdb->prefix}{$this->table}\n\t\t\t WHERE" . $this->wpdb->prepare($where, $prepare_args) . " LIMIT 1"); if (!$this->translation_id) { throw new InvalidArgumentException('No translation entry found for query: ' . serialize($where) . serialize($prepare_args)); } }
/** * Save entity to database. * * @return int|false */ public function save() { // Prepare query data. $set = array(); $values = array(); foreach ($this->values as $field => $value) { if ($field == 'id') { continue; } if ($value === null) { $set[] = sprintf('`%s` = NULL', $field); } else { $set[] = sprintf('`%s` = %s', $field, $this->formats[$field]); $values[] = $value; } } // Run query. if ($this->values['id']) { $res = $this->wpdb->query($this->wpdb->prepare(sprintf('UPDATE `%s` SET %s WHERE `id` = %d', $this->table_name, implode(', ', $set), $this->values['id']), $values)); } else { $res = $this->wpdb->query($this->wpdb->prepare(sprintf('INSERT INTO `%s` SET %s', $this->table_name, implode(', ', $set)), $values)); if ($res) { $this->values['id'] = $this->wpdb->insert_id; } } return $res; }
/** * Generate SQL from the whitelist. Uses the return format from wfLog::getWhitelistedIPs * * @see wfLog::getWhitelistedIPs * @param array $whitelisted_ips * @return string */ public function getBlockedIPWhitelistWhereClause($whitelisted_ips = null) { if ($whitelisted_ips === null) { $whitelisted_ips = wordfence::getLog()->getWhitelistedIPs(); } if (!is_array($whitelisted_ips)) { return false; } $where = ''; /** @var array|wfUserIPRange|string $ip_range */ foreach ($whitelisted_ips as $ip_range) { if (is_array($ip_range) && count($ip_range) == 2) { $where .= $this->db->prepare('IP BETWEEN %s AND %s', $ip_range[0], $ip_range[1]) . ' OR '; } elseif (is_a($ip_range, 'wfUserIPRange')) { $where .= $ip_range->toSQL('IP') . ' OR '; } elseif (is_string($ip_range) || is_numeric($ip_range)) { $where .= $this->db->prepare('IP = %s', $ip_range) . ' OR '; } } if ($where) { // remove the extra ' OR ' $where = substr($where, 0, -4); } return $where; }
function site_get_avatar($avatar, $id_or_email, $size, $default, $alt) { $email = ''; if (is_numeric($id_or_email)) { $id = (int) $id_or_email; $user = get_userdata($id); if ($user) { $email = $user->user_email; } } elseif (is_object($id_or_email)) { $email = $id_or_email->comment_author_email; } $forum_db = ''; $img_folder = ''; // No trailing slash $img_path = $img_folder . '/image.php?u='; $my_wpdb = new wpdb(DB_USER, DB_PASSWORD, $forum_db, DB_HOST); $myrows = $my_wpdb->get_var($my_wpdb->prepare("SELECT userid\n FROM " . $forum_db . ".vb_user\n WHERE email = %s LIMIT 1", array($email))); if ($myrows != '') { $img = $img_path . $myrows; } elseif ($avatar) { return $avatar; } else { $img = $default; } $my_avatar = '<img src="' . $img . '" alt="' . $alt . '" height="' . $size . '" width="' . $size . '" class="avatar avatar-50 photo grav-hashed grav-hijack" />'; return $my_avatar; }
/** * Compose WHERE clause based on parameters provided * @param string|array $field * @param mixed[optional] $value * @param string[optional] $operator AND or OR string, 'AND' by default * @return string */ protected function buildWhere($field, $value = NULL, $operator = NULL) { if (!is_array($field)) { $field = array($field => $value); } else { // shift arguments $operator = $value; } !is_null($operator) or $operator = 'AND'; // apply default operator value $where = array(); foreach ($field as $key => $val) { if (is_int($key)) { $where[] = '(' . call_user_func_array(array($this, 'buildWhere'), $val) . ')'; } else { if (!preg_match('%^(.+?) *(=|<>|!=|<|>|<=|>=| (NOT +)?(IN|(LIKE|REGEXP|RLIKE)( BINARY)?))?$%i', trim($key), $mtch)) { throw new Exception('Wrong field name format.'); } $key = $mtch[1]; if (is_array($val) and (empty($mtch[2]) or 'IN' == strtoupper($mtch[4]))) { $op = empty($mtch[2]) ? 'IN' : strtoupper(trim($mtch[2])); if (count($val)) { $where[] = $this->wpdb->prepare("{$key} {$op} (" . implode(', ', array_fill(0, count($val), "%s")) . ")", $val); } } else { $op = empty($mtch[2]) ? '=' : strtoupper(trim($mtch[2])); $where[] = $this->wpdb->prepare("{$key} {$op} %s", $val); } } } return implode(" {$operator} ", $where); }
/** * @param string $slug * @param string|bool $language * * @return string */ function get_translated_slug($slug, $language = false) { if ($slug) { $current_language = $this->sitepress->get_current_language(); $language = $language ? $language : $current_language; if (!isset($this->translated_slugs[$slug][$language])) { $slugs_translations = $this->wpdb->get_results($this->wpdb->prepare("SELECT t.value, t.language\r\n\t\t\t\t\t\t\t\t\t\tFROM {$this->wpdb->prefix}icl_strings s\r\n\t\t\t\t\t\t\t\t\t\tJOIN {$this->wpdb->prefix}icl_string_translations t ON t.string_id = s.id\r\n\t\t\t\t\t\t\t\t\t\tWHERE s.name = %s\r\n\t\t\t\t\t\t\t\t\t\t AND (s.context = %s OR s.context = %s)\r\n\t\t\t\t\t\t\t\t\t\t\tAND t.status = %d\r\n\t\t\t\t\t\t\t\t\t\t\tAND t.value <> ''", 'URL slug: ' . $slug, 'default', 'WordPress', ICL_TM_COMPLETE)); foreach ($slugs_translations as $translation) { $this->translated_slugs[$slug][$translation->language] = $translation->value; } // Add empty values for languages not found. foreach ($this->sitepress->get_active_languages() as $lang) { if (!isset($this->translated_slugs[$slug][$lang['code']])) { $this->translated_slugs[$slug][$lang['code']] = ''; } } } if ($this->translated_slugs[$slug][$language]) { $has_translation = true; $slug = $this->translated_slugs[$slug][$language]; } else { $has_translation = false; } if ($has_translation) { return $slug; } } else { $has_translation = true; } return $has_translation ? $slug : $this->st_fallback($slug, $language); }
/** * Builds query. * * @since 1.0.0 * * @access protected * @param string $table The table name. * @param array|string $columns The array of columns to select. * @param array $criteria The array of conditions. * @return string The query string. */ protected function _prepareQuery($table, $columns, $criteria) { $where = '1 = 1'; $params = array(); foreach ($criteria as $column => $value) { $pattern = '%s'; if (is_null($value)) { $pattern = '%s AND `%s` IS NULL'; } elseif (is_numeric($value)) { $pattern = '%s AND `%s` = %%d'; $params[] = $value; } else { $pattern = '%s AND `%s` = %%s'; $params[] = $value; } $where = sprintf($pattern, $where, $column); } if (is_array($columns)) { $columns = implode(', ', $columns); } $query = sprintf('SELECT %s FROM %s WHERE %s', $columns, $table, $where); if (!empty($params)) { $query = $this->_wpdb->prepare($query, $params); } return $query; }
/** * @param int $limit * @return mixed */ public function getTopFailedLogins($limit = 10) { $interval = 'UNIX_TIMESTAMP(DATE_SUB(NOW(), interval 7 day))'; switch (wfConfig::get('email_summary_interval', 'weekly')) { case 'daily': $interval = 'UNIX_TIMESTAMP(DATE_SUB(NOW(), interval 1 day))'; break; case 'monthly': $interval = 'UNIX_TIMESTAMP(DATE_SUB(NOW(), interval 1 month))'; break; } $results = $this->db->get_results($this->db->prepare(<<<SQL SELECT *, sum(fail) as fail_count, max(userID) as is_valid_user FROM {$this->db->base_prefix}wfLogins WHERE fail = 1 AND ctime > {$interval} GROUP BY username ORDER BY fail_count DESC LIMIT %d SQL , $limit)); return $results; }
/** * Get a term by its term taxonomy ID. * * @param int $term_taxonomy_id Term taxonomy ID. * * @return array */ private function get_term_by_term_taxonomy_id($term_taxonomy_id) { $sql = "\nSELECT t.term_id, t.name, tt.taxonomy\nFROM {$this->wpdb->terms} t, {$this->wpdb->term_taxonomy} tt\nWHERE tt.term_id = t.term_id AND tt.term_taxonomy_id = %d\nLIMIT 1"; $query = $this->wpdb->prepare($sql, $term_taxonomy_id); $result = $this->wpdb->get_row($query, ARRAY_A); // $result might be NULL, but we need a predictable return type. return empty($result) ? array() : $result; }
/** * @param string $iso Something like de_AT * * @param string $field the field which should be queried * @return mixed */ public function get_lang_data_by_iso($iso, $field = 'native_name') { $iso = str_replace('_', '-', $iso); $query = $this->wpdb->prepare("SELECT `{$field}`\n\t\t\tFROM `{$this->table_name}`\n\t\t\tWHERE `http_name` = " . "%s LIMIT 1", $iso); $result = $this->wpdb->get_var($query); $return = NULL === $result ? '' : $result; return $return; }
/** * Get a term by its term_taxonomy_id. * * @param int $tt_id term_taxonomy_id * @return array */ private function get_term_by_tt_id($tt_id) { $sql = "\nSELECT terms.`term_id`, terms.`name`, terms.`slug`, tax.`taxonomy`\nFROM {$this->wpdb->terms} terms\n INNER JOIN {$this->wpdb->term_taxonomy} tax\n ON tax.`term_taxonomy_id` = %d\nWHERE tax.`term_id` = terms.`term_id`\nLIMIT 1"; $query = $this->wpdb->prepare($sql, $tt_id); $result = $this->wpdb->get_row($query, ARRAY_A); // $result might be NULL, but we need a predictable return type. return empty($result) ? array() : $result; }
/** * Used internally to generate an SQL string for searching across multiple columns. * * @since 4.6.0 * @access protected * * @param string $string Search string. * @param array $columns Columns to search. * * @return string Search SQL. */ protected function get_search_sql($string, $columns) { $like = '%' . $this->db->esc_like($string) . '%'; $searches = array(); foreach ($columns as $column) { $searches[] = $this->db->prepare("{$column} LIKE %s", $like); } return '(' . implode(' OR ', $searches) . ')'; }
/** * @param $criteria * @param $cast * @return array|null|object */ public function findBy($criteria, $cast = false) { $objectArray = array(); $returnType = $cast ? OBJECT : ARRAY_A; $criteria = $this->parseCriteria($criteria); if (class_exists($this->modelClass)) { $model = new $this->modelClass(); $tableName = $this->wpdb->prefix . $model::TABLE_NAME; $res = $this->wpdb->get_results($this->wpdb->prepare("\n SELECT *\n FROM {$tableName}\n WHERE {$criteria["where"]}\n {$criteria["order"]}\n ", $criteria["values"]), $returnType); if ($cast) { foreach ($res as $row) { $objectArray[] = $this->cast($this->modelClass, $row); } } return $cast ? $objectArray : $res; } return null; }
/** * @param array $args * @param string $output_type * @return int|mixed */ public function find($args, $output_type = OBJECT) { $args = wp_parse_args($args, array('select' => '*', 'offset' => 0, 'limit' => 1, 'orderby' => 'id', 'order' => 'DESC', 'email' => '', 'method' => '', 'datetime_after' => '', 'datetime_before' => '', 'include_errors' => true)); $where = array(); $params = array(); // build general select from query $query = sprintf("SELECT %s FROM `%s`", $args['select'], $this->table_name); // add email to WHERE clause if ('' !== $args['email']) { $where[] = 'email LIKE %s'; $params[] = '%%' . $this->db->esc_like($args['email']) . '%%'; } // add method to WHERE clause if ('' !== $args['method']) { $where[] = 'method = %s'; $params[] = $args['method']; } // add datetime to WHERE clause if ('' !== $args['datetime_after']) { $where[] = 'datetime >= %s'; $params[] = $args['datetime_after']; } if ('' !== $args['datetime_before']) { $where[] = 'datetime <= %s'; $params[] = $args['datetime_before']; } if (!$args['include_errors']) { $where[] = 'success = %d'; $params[] = 1; } // add where parameters if (count($where) > 0) { $query .= ' WHERE ' . implode(' AND ', $where); } // prepare parameters if (!empty($params)) { $query = $this->db->prepare($query, $params); } // return result count if ($args['select'] === 'COUNT(*)') { return (int) $this->db->get_var($query); } // return single row if ($args['limit'] === 1) { $query .= ' LIMIT 1'; return $this->db->get_row($query); } // perform rest of query $args['limit'] = absint($args['limit']); $args['offset'] = absint($args['offset']); $args['orderby'] = preg_replace("/[^a-zA-Z]/", "", $args['orderby']); $args['order'] = preg_replace("/[^a-zA-Z]/", "", $args['order']); // add ORDER BY, OFFSET and LIMIT to SQL $query .= sprintf(' ORDER BY `%s` %s LIMIT %d, %d', $args['orderby'], $args['order'], $args['offset'], $args['limit']); return $this->db->get_results($query, $output_type); }
/** * Records transaction into database. * * @access protected * @param type $user_id * @param type $sub_id * @param type $amount * @param type $currency * @param type $timestamp * @param type $paypal_ID * @param type $status * @param type $note */ protected function _record_transaction($user_id, $sub_id, $amount, $currency, $timestamp, $paypal_ID, $status, $note) { $data = array('transaction_subscription_ID' => $sub_id, 'transaction_user_ID' => $user_id, 'transaction_paypal_ID' => $paypal_ID, 'transaction_stamp' => $timestamp, 'transaction_currency' => $currency, 'transaction_status' => $status, 'transaction_total_amount' => (int) round($amount * 100), 'transaction_note' => $note, 'transaction_gateway' => $this->gateway); $existing_id = $this->db->get_var($this->db->prepare("SELECT transaction_ID FROM " . MEMBERSHIP_TABLE_SUBSCRIPTION_TRANSACTION . " WHERE transaction_paypal_ID = %s LIMIT 1", $paypal_ID)); if (!empty($existing_id)) { $this->db->update(MEMBERSHIP_TABLE_SUBSCRIPTION_TRANSACTION, $data, array('transaction_ID' => $existing_id)); } else { $this->db->insert(MEMBERSHIP_TABLE_SUBSCRIPTION_TRANSACTION, $data); } }
/** * Get the data for a particular form. * * @author Jeremy Pry * * @param int $form_id The ID of the form to retrieve. * * @return array The array of form data. */ public function get_form($form_id) { // Retrieve the raw data from the DB. $form_results = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM {$this->prefixed_table_name} WHERE id = %d", $form_id), ARRAY_A); // If there were no results, then return an empty array. if (null === $form_results) { /** * Filter the form data that is retrieved from the Database. * * @param array $form_settings The array of processed form data. * @param int $form_id The form ID. * @param array $form_results The raw data from the database. */ return apply_filters('yikes-easy-mailchimp-extender-form-data', array(), $form_id, $form_results); } // Populate array with new settings. $form_settings = $this->prepare_data_for_display($form_results); /** This filter is documented in this function above. */ return apply_filters('yikes-easy-mailchimp-extender-form-data', $form_settings, $form_id, $form_results); }
/** * Returns all ids from DB suitable for given restriction. * E.g. all comment_id values where comment_post_id = 1 * @param string $entityName * @param array $where * @return array */ private function getIdsForRestriction($entityName, $where) { $idColumnName = $this->dbSchemaInfo->getEntityInfo($entityName)->idColumnName; $table = $this->dbSchemaInfo->getPrefixedTableName($entityName); $sql = "SELECT {$idColumnName} FROM {$table} WHERE "; $sql .= join(" AND ", array_map(function ($column) { return "`{$column}` = %s"; }, array_keys($where))); $ids = $this->database->get_col($this->database->prepare($sql, $where)); return $ids; }