Is there any method to close connection similar to mysql_close() for wpdb in WordPress? Is it not necessary to close connection for global wpdb?
18920
Is there any method to close connection similar to  for  in WordPress?  Is it not necessary to close connection for global $wpdb?
113299
I'm trying to learn a bit more about the details of proper database construction and ran across something that confuses me. In a current Wordpress installation, I'm finding varchar fields used for indexes which are longer than the 191 characters, which the documentation seems to say is the max. I'm running MariaDB 10.x which I believe matches up with MySQL 5.7, and the  confirms the limit when using utf8mb4_unicode_ci collation and compact as the format.  I'm finding varchar(200) and varchar(255) indexed fields, e.g. wp_postmeta, the field meta_key is varchar(255). Am I wrong or confused on this? The db is using the InnoDB engine. Thanks for any clarification.
115994
What is the difference between $GLOBALS['wp_the_query'] and global $wp_query?  Why prefer one over the other?
112966
I want to make sure all of the data in my plugins/themes is handled securely  before entering the database and before being output to the browser. My problem is that there are situations where the API handles the sanitization for you -- like when saving post meta fields -- and others where the plugin/theme author is wholly responsible for doing it -- like when saving custom settings.  For the scope of this question, I'm not concerned about validating data at the domain level -- e.g., checking that an Age field on a form is between 0 and 120, or that an e-mail address is valid. I'm only concerned about security -- e.g., escaping SQL queries to avoid SQL injection when saving to the database, or sanitizing data that's output to HTML templates to avoid XSS.  For output sanitization, I know that you always need to use functions like esc_html() and esc_attr() when echo'ing variables into HTML templates. But, what about when using ? Do they all sanitize the output already? If so, for which context (general HTML, tag attributes, etc)? Some functions have variants for different contexts (like the_title_attribute(), but most don't.  For input sanitization, I know that I need to use $wpdb-&gt;prepare() when making manual queries, but what about when using the Settings API to create a plugin settings page, or saving post meta fields for a custom post type?  Right now I've just been digging through Core and reading tutorials every time I use a function to find out if it sanitizes or not, but that's error-prone and time consuming. I'm hoping to find some kind of comprehensive list of all the possible situations and whether or not the API handles it. e.g.,  API validates/sanitizes   Saving post meta with update_postmeta() Saving user meta with update_user_meta() Outputting a post title - use the contextually appropriate variant of the_title() etc   You have to manually validate/sanitize   Saving plugin options with the Settings API. Pass a callback as the 3rd parameter of register_setting(). Direct database queries: Wrap the query in $wpdb-&gt;prepare(). Outputting variables in HTML. Use esc_attr(), esc_html(), etc etc   I'd also be interested to understand why the API provides it in certain situations, but not others. I'm assuming it has something to do with the unknown nature of the data, but would love to hear a thorough explanation.
59811
Here is the script to create my tables:   CREATE TABLE clients (    client_i INT(11),    PRIMARY KEY (client_id) ); CREATE TABLE projects (    project_id INT(11) UNSIGNED,    client_id INT(11) UNSIGNED,    PRIMARY KEY (project_id) ); CREATE TABLE posts (    post_id INT(11) UNSIGNED,    project_id INT(11) UNSIGNED,    PRIMARY KEY (post_id) );   In my PHP code, when deleting a client, I want to delete all projects posts:  DELETE  FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id;   The posts table does not have a foreign key client_id, only project_id. I want to delete the posts in projects that have the passed client_id.  This is not working right now because no posts are deleted.
72493
After a certain amount of time WP logs out all users and forces them to log back in again. For development environments on my local machine this is obnoxious and absolutely unnecessary.  Is there an API-driven way of disabling the auto-logout indefinitely? Ideally I'd like something I can add to wp-config.php along with other dev-setup-related settings.  A plugin would be overkill for me so I won't consider it an answer, but you might as well post it as an option.
82000
I am trying to create the following trigger:      CREATE TRIGGER update_customers AFTER INSERT ON wp_usermeta     FOR EACH ROW      BEGIN             if new.wp_metakey = first_name then insert into test_customer(first_name) values (new.wp_meta_value);     END   I keep getting a 1064 error that says, "You have an error in your SQL syntax; check the manual that corresopons to your MySQL server version for the right syntaxt to use near " at line 5"  What am I doing wrong?
65043
Apparently, I can connect to MySQL (at least from my localhost) without having to provide any username or password. I can even put anything as username, as long as the password is empty. I have access to the information_schema and test databases. I can create tables. If I run SELECT USER() it returns the proper value randomstring@localhost, where the random string is whatever I used for username when I connected.  The mysql.user table contains root@localhost, root@127.0.0.1, @localhost and pma@localhost. I manually set encrypted passwords to all the records (UPDATE user SET password=...) and only root has any privileges, the other two records have "N" for all privileges. That record with the empty username looks suspicious, but I don't think it has anything to do with this and I think it was there from the beginning.  To make matters worse, if I add a user with a password, I can only connect using empty string as password (just like if I put anything as username). If I try to connect using the username I created and password I supplied when creating it (CREATE USER .. IDENTIFIED BY ..) it doesn't work.  Does anyone know what is wrong and how I can fix this?  Note: I am using MySQL 5.5.16 for Windows, provided by the XAMPP package.
73014
If I write a private plugin, is there any way to use the WordPress auto-update mechanism to update it?  I want to encapsulate the functionality, but it's specific to my own 5 or so blogs, so it's not a good candidate for the public plugins resource. But I love the easy-updating mechanism.  Is there a way to do this?
93640
How CPU intensive is opening and closing of a DB connection (for a web app) in MySQL   ... when the DB software is on localhost? ... when the DB software is on another machine?
30444
So...here is part of my code for a plugin.  I'm a newb of sorts so be kind.  I've read up on global variables but I can't seem to get it to work and I've read you shouldn't use them anyway.  So what would be the best way to write the code below without having to re-declare the variables for each function?  Here is the  if necessary.  // Display the product badge on the shop page  add_action( 'woocommerce_after_shop_loop_item_title', 'wc_simple_product_badge_display_shop', 30 ); function wc_simple_product_badge_display_shop() {     $title = get_post_meta( get_the_ID(), '_wc_simple_product_badge_title', true ); // badge title     $class = get_post_meta( get_the_ID(), '_wc_simple_product_badge_class', true ); // badge class     $duration = get_post_meta( get_the_ID(), '_wc_simple_product_badge_duration', true ); // badge duration     $postdate = get_the_time( 'Y-m-d' ); // post date     $postdatestamp = strtotime( $postdate ); // post date in unix timestamp     $difference = round ((time() - $postdatestamp) / (24*60*60));  // difference in days between now and product's post date      if ( !empty( $title ) &amp;&amp; empty( $duration ) || !empty( $title ) &amp;&amp; $difference &lt;= $duration ){ // Check to see if there is a title and the product is still within the duration timeframe if specified         $class = !empty( $class ) ? $class : '';         echo '&lt;span class="wc_simple_product_badge ' . $class . '"&gt;' . $title . '&lt;/span&gt;';     } }  // Display the product badge on the single page  add_filter( 'woocommerce_single_product_image_html', 'wc_simple_product_badge_display_single' );     function wc_simple_product_badge_display_single( $img_html ) {     $title = get_post_meta( get_the_ID(), '_wc_simple_product_badge_title', true ); // badge title     $class = get_post_meta( get_the_ID(), '_wc_simple_product_badge_class', true ); // badge class     $duration = get_post_meta( get_the_ID(), '_wc_simple_product_badge_duration', true ); // badge duration     $single_opt = get_post_meta( get_the_ID(), '_wc_simple_product_badge_single_page_option', true ); // badge on single page     $postdate = get_the_time( 'Y-m-d' ); // post date     $postdatestamp = strtotime( $postdate ); // post date in unix timestamp     $difference = round ((time() - $postdatestamp) / (24*60*60));  // difference in days between now and product's post date      if ( !empty( $title ) &amp;&amp; empty( $duration ) &amp;&amp; $single_opt === 'yes' || !empty( $title ) &amp;&amp; $difference &lt;= $duration &amp;&amp; $single_opt === 'yes' ){ // Check to see if there is a title and the product is still within the duration timeframe ()if specified) and the checkbox is checked to show on single page view         $class = !empty( $class ) ? $class : '';         echo '&lt;span class="wc_simple_product_badge ' . $class . '"&gt;' . $title . '&lt;/span&gt;';         return $img_html; }      elseif ( $single_opt === 'no' ) { // Check to see if the checkbox is unchecked to show on single page view         return $img_html;     }  }
2362
I have a Widget which I am creating but my quesiton is how do I access my custom table which I created via my plugin. I am attempting to fill the dropdown from the table called tfp which contains the column liters which I wish to popluate the values into the drop down   class my_plugin extends WP_Widget {  // constructor function my_plugin() {         parent::WP_Widget(false, $name = __('Thomsons Fuels Widget', 'wp_widget_plugin') );  }  // widget form creation function form($instance) {  //Check values if( $instance) {  $title = esc_attr($instance['title']);  $dropdown= esc_attr($instance['dropdown']);  $textarea = $instance['textarea'];  } else {  $title = '';  $textarea = ''; } ?&gt;   &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id('dropdown'); ?&gt;"&gt; &lt;?php _e('Liters',   'wp_widget_plugin'); ?&gt;&lt;/label&gt; &lt;select&gt; &lt;option value="volvo"&gt;Volvo&lt;/option&gt; &lt;/select&gt;  &lt;/p&gt;   How I created the table in the plugin   global $wpdb; global $custom_table_example_db_version;  $table_name = $wpdb-&gt;prefix . 'tfp'; // do not forget about tables prefix  // sql to create your table // NOTICE that: // 1. each field MUST be in separate line // 2. There must be two spaces between PRIMARY KEY and its name //    Like this: PRIMARY KEY[space][space](id) // otherwise dbDelta will not work $sql = "CREATE TABLE " . $table_name . " (   id int(11) NOT NULL AUTO_INCREMENT,   liters VARCHAR(100) NOT NULL,   price VARCHAR(100) NOT NULL,      postcodearea varchar(20) NULL,         dft varchar(20) NULL,   PRIMARY KEY  (id) );";  // we do not execute sql directly // we are calling dbDelta which cant migrate database require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql);  // save current database version for later use (on upgrade) add_option('custom_table_example_db_version', $custom_table_example_db_version);
11941
I have added a custom/secondary query to a template file/custom page template; how can I make WordPress use my custom query for pagination, instead of using the main query loop's pagination?  Addendum  I have modified the main loop query via . Why isn't pagination working, and how do I fix it?
31246
The shortcode produced by this function - a list of all sites in a multisite - outputs above the content in the loop, no matter where it is placed in the editor.  I've looked at the other related questions and answers on WPSE and realize that it has to do with the function using echo instead of return, but it's not as easy as replacing the instances of echo with return in the function below. Or adding echo=0 with a WP function like wp_list_pages()  Any ideas? Where is the function that needs to be returned instead of echoed?  // Output a single menu item function projects_menu_entry($id, $title, $link_self) {     global $blog_id;     if ($link_self || $id != $blog_id) {         echo '&lt;li&gt;';         if ($id == $blog_id) {             echo '&lt;strong&gt;';         }         $url = get_home_url($id);         if (substr($url, -1) != '/') {             // Note: I added a "/" to the end of the URL because WordPress             // wasn't doing that automatically in v3.0.4             $url .= '/';         }         echo '&lt;a href="' . $url . '"&gt;' . $title . '&lt;/a&gt;';         if ($id == $blog_id) {             echo '&lt;/strong&gt;';         }         echo '&lt;/li&gt;';     } }  // Output the whole menu // If $link_self is false, skip the current site - used to display the menu on the homepage function projects_menu($link_self = true) {     global $wpdb;      echo '&lt;ul&gt;';      projects_menu_entry(1, 'Home', $link_self);      $blogs = $wpdb-&gt;get_results("         SELECT blog_id         FROM {$wpdb-&gt;blogs}         WHERE site_id = '{$wpdb-&gt;siteid}'         AND spam = '0'         AND deleted = '0'         AND archived = '0'         AND blog_id != 1     ");      $sites = array();     foreach ($blogs as $blog) {         $sites[$blog-&gt;blog_id] = get_blog_option($blog-&gt;blog_id, 'blogname');     }      natsort($sites);     foreach ($sites as $blog_id =&gt; $blog_title) {         projects_menu_entry($blog_id, $blog_title, $link_self);     }     echo '&lt;/ul&gt;'; }  // Adds a [bloglist] shortcode  function bloglist_shortcode($atts) {     projects_menu(false); }  add_shortcode('bloglist', 'bloglist_shortcode');
26567
How can I execute a query that connects to different databases?  I have the following query, and I need to rewrite it for Drupal.  SELECT a.empid, b.empname FROM db1..empidmaster a, db2..emplist b WHERE a.empid = b.empid   How can I rewrite the query using db_query(), or db_select()?
41247
A couple of the options are:  $connection = {my db connection/object};  function PassedIn($connection) { ... }  function PassedByReference(&amp;$connection) { ... }  function UsingGlobal() {     global $connection;     ... }   So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference.  I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities.  The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.
61666
In reading I am not sure if the issue below could have something to do with needing a custom wordpress ajax handler? All of these functions are inside my functions.php file. I have a couple of PHP functions that are supposed to pass information from one to another. The an AJAX call to the final function should produce the final result through that call. Its not happening. My count results in 0 and I am not understanding why. If I replace my query with a static array like [44,55,99,33] then it will pass the values ok. Likewise if I keep the query and simply replace the $id in the query and make it a static id such as '20' then it works. I would think that the id was the issue then and it wasnt pulling properly but it seems to work ok just not pass? function idx(){     global $wpdb, $id;       $getId = $_SERVER['REQUEST_URI'];     $ecp = explode('/', $getId);     if($ecp[3] != ''){         $id = $ecp[3];     }         return $id; } add_action( 'after_setup_theme', 'idx' );  =============================================== function Total_Result(){     global $wpdb;     $id = idx();        /*$resultx = [44,88,59,52];*/ ;      $resultx = $wpdb-&gt;get_results( $wpdb-&gt;prepare(&quot;SELECT * FROM {$wpdb-&gt;prefix}custom_form_submission_conversation as cc LEFT JOIN {$wpdb-&gt;prefix}custom_form_submission as cs on cc.fsid ='$id' WHERE fsid='$id'&quot; ));          $resultxs = array($resultx);          $total_result =  count($resultxs[0]);     echo  $total_result; }  when I var_dump $resultx I get: array(3) { [0]=&gt; object(stdClass)#1256 (36) { [“cid”]=&gt; string(3) “167” [“fsid”]=&gt; string(2) “20” [“specified_date”]=&gt; string(3) “yes” [“price_quote”]=&gt; string(4) “1140” [“posted_by”]=&gt; string(9) “dc_vendor” [“limit_count”]=&gt; string(1) “1” [“read_unread”]=&gt; string(1) “1” [“vendor_response”]=&gt; string(4) “zero” [“date_created”]=&gt; string(19) “2021-04-15 11:39:08” }   [1]=&gt; object(stdClass)#1257 (36) { [“cid”]=&gt; string(3) “186” [“fsid”]=&gt; string(2) “20” [“specified_date”]=&gt; string(3) “Yes” [“price_quote”]=&gt; string(3) “602” [“posted_by”]=&gt; string(8) “customer” [“limit_count”]=&gt; string(1) “1” [“read_unread”]=&gt; string(1) “1” [“vendor_response”]=&gt; string(4) “zero” [“date_created”]=&gt; string(19) “2021-04-15 11:39:08” }   [2]=&gt; object(stdClass)#1258 (36) { [“cid”]=&gt; string(3) “188” [“fsid”]=&gt; string(2) “20” [“specified_date”]=&gt; string(3) “yes” [“price_quote”]=&gt; string(4) “1017” [“posted_by”]=&gt; string(9) “dc_vendor” [“limit_count”]=&gt; string(1) “1” [“read_unread”]=&gt; string(1) “0” [“vendor_response”]=&gt; string(4) “zero” [“date_created”]=&gt; string(19) “2021-04-15 11:39:08” } }   so then I try and pass that data like so: function getvendorresponsestatus() {     global $wpdb; $id = idx();          $total_resultx = Total_Result($id);         die; }  Ive tried with and without the die();. The AJAX call is: setInterval(function(){     var ffiidd = jQuery('#ffiidd').val();     var ajaxurl = &quot;&lt;?php echo admin_url('admin-ajax.php'); ?&gt;&quot;;          jQuery.post(ajaxurl, {         action: &quot;vendorAjaxprog&quot;,         ffiidd: ffiidd     }, function(data) {         console.log(data);         jQuery.post(ajaxurl, {             action: &quot;getvendorresponsestatus&quot;, //&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; this is the action that calls the function             fsid : ffiidd         },         function(datas) {             console.log('+ datas);             jQuery('.cust_vendor_top').html(datas);         });         if(data == 0){}else{             jQuery('.ajaxreload').html(data);                                     }     });               }, 5000);/*==30 seconds==*/  So the question is why wont it pass along the query array information but it passes a basic array or it will pass if I change the id in the query to be static? I know the query is good because of when I var_dumped it, I have results before I get to the Total_Result() function.