Web Shakehands
Web Shakehands

Language


Get information from the WordPress database using wpdb->prepare [plugin production]



When acquiring information from a database, normal PHP uses PDO and other kinds.
What about WordPress?

WordPress has some useful functions.
By using $wpdb-> prepare function, it is possible to connect the database safely for security.


I will describe below.

This is an example of searching information from a database with a specific page ID and date.
The ID is 15, the date and time will be 2019-7-25.

First, get the database class in global $wpdb;
$wpdb is the instance that can interact with the WordPress database, and can be used by declaring it as a global variable.

Next, substitute the table name.

For more information, this article is also helpful.
https://global-s-h.com/article/article.php?id=27


And then comes $wpdb-> prepare. Concerning the security, the second and third arguments are used to assign values to the placeholders.
This time, number "15" of $post_id is assigned as %d. And, "2019-7-25" which is $current_now will be inserted to %s.

This assignment depends on the version of PHP you are using, but the point is that you have to use this.
Even if there is nothing to assign, please assign in either the second or the third argument.

If you do not do this, some PHP versions may not work.

In addition, although not recommended very much, but there is also a method of emptying the double quotation of the second argument as follows.

More details for $wpdb-> prepare can be found in Codex.
Go to Codex page


And use "get_results" to get these information.
This time, the information acquired in $query is assigned to $rows, and it will be assigned with array.

This is written in Codex for "get_results"
Go to Codex page


When getting data from a WordPress database, it's a good idea to use these protected functions.



このエントリーをはてなブックマークに追加

This article title

Get information from the WordPress database using wpdb->prepare [plugin production]

Previous article How to pass array to the database by using "update_option". WordPress Plugin Creation


WordPress Plugin creation Article !

2019-07-25 Get information from the WordPress database using wpdb->prepare [plugin production] NEW!


2019-07-23 How to pass array to the database by using "update_option". WordPress Plugin Creation


2019-07-17 How to create a database table from a WordPress plugin


2019-07-13 Use current_time () when dealing with WordPress dates!


See all the articles list

Just enter your E-mail and you will receive free
mail magazine about how to make your website etc.
E-mail:
  

Go to top