Hongmu Notes
Home page › Program Notes › wordpress database query operation
Program Notes wordpress

wordpress database query operation

wordpress database query operation

First, connect to the database

To connect to the WordPress database, you need to include the following in the PHP file:wp-config.phpFile. This file contains database configuration information and other constants related to the WordPress installation.

The following is a simple example demonstrating how to introducewp-config.phpLoad the file and obtain the database connection:

// 引入 wp-config.php 文件
require_once('path/to/wp-config.php');

// 获取数据库连接
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
$dbh = new PDO($dsn, DB_USER, DB_PASSWORD);

In this example, we first userequire_once()Function Introductionwp-config.phpFile. Then, we use the constants defined in that file (such asDB_HOST、DB_NAME、DB_USER和DB_PASSWORD) to obtain a PDO database connection. Here, the PDO (PHP Data Object) library is used to connect to the database; of course, you can also use other libraries or functions for database connection—specific methods can be found in relevant documentation or tutorials.

For Your Attention,wp-config.phpThe file contains sensitive information related to the database, such as the database username and password; therefore, when deploying the website, you should ensure the file's security—for example, by placing it in a directory that the web server cannot access directly.

Execute SQL operations

Once introducedwp-config.phpOnce the file has obtained a database connection, you can use the functions provided by WordPress to perform database operations. The following is a simple example demonstrating how to querywp_postsAll article titles in the table:

 Hidden content: You can view it after logging in
// 引入 wp-config.php 文件
require_once('path/to/wp-config.php');

// 获取数据库连接
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
$dbh = new PDO($dsn, DB_USER, DB_PASSWORD);

// 执行查询
$results = $dbh->query("SELECT post_title FROM wp_posts");

// 处理结果
foreach ($results as $result) {
    echo $result['post_title'] . "<br/>";
}

In this example, we first userequire_once()Function Introductionwp-config.phpFile, then usePDOThe database connection is obtained from the database. Next, we use$dbh->query()The function executes a SQL query and stores the results in a PDOStatement object. Finally, we use aforeachIterate through the result set and output the title of each article.

Note that the query statement here useswp_postsTable name: this is because WordPress adds a prefix when creating a database table (the default iswp_), to distinguish between different WordPress installations. Therefore, if you use a different prefix when installing WordPress, the table name in the query statement should also be modified accordingly.

It should be noted that when performing database queries, care should be taken to avoid SQL injection attacks; therefore, the following should be used:$dbh->prepare()Prepare safe SQL queries using function parameters to prevent input data from being misinterpreted as SQL code. For example:

 Hidden content: You can view it after logging in
$query = $dbh->prepare("SELECT post_title FROM wp_posts WHERE post_author = :author");
$query->bindParam(':author', $author_id, PDO::PARAM_INT);
$query->execute();

In this example, we use$dbh->prepare()The function prepares a secure query and then uses it.$query->bindParam()Bind the function to the input parameters. This ensures that the query is safe and prevents input parameters from being mistakenly interpreted as SQL code.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

What should I do if the Redis Object Cache plug-in cannot be linked after changing the password in wordpress redis?

What should I do if the Redis Object Cache plug-in cannot be linked after changing the password in wordpress redis? Program Notes wordpress

Problem description: I am using the Baota Panel for my WordPress site server. I have installed PHP 8.0 and configured Redis in the extensions panel; I have also installed the Redis Object Cache plugin on WordPress. Under normal circumstances, no additional action is required—the site starts up immediately and works fine. However, leaving Redis without a password is highly insecure and constitutes a security vulnerability; therefore, I believe it is better to set a password for Redis,...
👁 531
How to cancel revisions and automatically save drafts in WordPress?

How to cancel revisions and automatically save drafts in WordPress? Program Notes wordpress

WordPress has a feature that automatically stores revisions of articles; each time you edit an article, a record is created in the backend, and each revision inserts a new record into the posts table. Because article revisions and automatic saving interact with each other, an article's ID tends to grow larger and larger over time. While this does not cause significant problems for your WordPress site, having too many article versions can place a substantial negative load on your hosting space and database...
👁 625
Detailed tutorial on migrating imperial cms blog data to wordpress

Detailed tutorial on migrating imperial cms blog data to wordpress Program Notes wordpress

PS1: Second revision; currently, data migration between categories, posts, and tags is supported. PS2: If the post IDs consistently do not align, you can try clearing the WordPress post category table and its relationship table. I previously used Typecho for my blog; later, I migrated to Empire, but Empire has so many features that using it for a blog feels like overkill! Moreover, when I use my blog, I often record important code snippets that I have painstakingly developed...
👁 809
Wordpress has a problem with image transcoding causing the page to freeze.

Wordpress has a problem with image transcoding causing the page to freeze. Program Notes wordpress

Last night, while uploading an image, for some reason the image was automatically transcoded; the transcoding format was BASE64 encoding. One approach is to upload an image to a server and then access the link; the image will then be displayed. Another method is to transcode the image directly; by accessing the converted CODE directly, the image can be viewed. Problem description: When an image is relatively small—only a few KB in size—transcoding it and embedding the result on the website can help avoid...
👁 450
WordPress MySQL database table and sub-table structure function description

WordPress MySQL database table and sub-table structure function description Program Notes wordpress

WordPress uses a MySQL database. The structure of its data tables differs somewhat from conventional practices: while some data is stored in the usual table format, other data is stored as data elements; the data-element approach is less intuitive when viewed directly. To become a developer, we must master the basic structure of the WordPress database and apply it in our own plugins or themes to write to and read from the database. I. Data Tables: As of WordPress...
👁 649
wordpress link database to perform update sql operation

wordpress link database to perform update sql operation Program Notes wordpress

To execute an update SQL statement in WordPress, you first need to create a new PHP file and include WordPress's core files; this includes the database connection and the definition of the $wpdb object. Below is an example: &lt;?php // Include WordPress's core files require_once(dirname(__FILE__)...
👁 426

Recommended reading

Commonly used regular filters for locomotive collection

Commonly used regular filters for locomotive collection Summary of pitfalls

To obtain standardized content, considerable effort must be devoted to data collection! Develop well-defined data-collection rules. My criteria for evaluating standardized content: each paragraph must be &lt;p&gt;&amp;&lt;/p&gt;; there must be no redundant HTML tags or characters unrelated to the topic; data extraction method: select regular-expression extraction, then combine the results and insert them into &lt;p&gt;[Parameter1]&amp;&lt;/p&gt;; some content does not have a clear beginning or end...
👁 579
Apple cmsV10 imitation site actual combat personal vlog video

Apple cmsV10 imitation site actual combat personal vlog video Program Notes Apple cms

Contact information 🔒 Hidden content: Check after commenting. I am Hongmu, QQ1810216796 communication group: 958972323 If you have any questions, please join the group to communicate. Preparation of website imitation tools in the early stage: https://wwi.lanzoup.com/iHqCOs7m06d Configuration path: /template/skin/static/PHPstudy: Windows version of phpstu…
👁 680
(PC+WAP) Marketing plastic sheet purification and environmental protection equipment website pbootcms template Green environmental protection hardware sheet website template download 0101

(PC+WAP) Marketing plastic sheet purification and environmental protection equipment website pbootcms template Green environmental protection hardware sheet website template download 0101 Practical Collection pbootcmstemplate

A PbootCMS marketing template designed for the plastic sheeting, cleanroom environmental protection equipment, and hardware sheeting industries. It features a green design and supports both PC and WAP devices. The page layout emphasizes product display and environmental sustainability, helping eco-materials companies establish a green brand image online and attract targeted customers. Template preview | Installation instructions | Website backend: /admin.php | Account: admin | Password: admin | Unzip password: www...
👁 346
(Adaptive mobile phone version) Responsive SEO tutorial information website pbootcms template SEO blog optimization website source code download 0257

(Adaptive mobile phone version) Responsive SEO tutorial information website pbootcms template SEO blog optimization website source code download 0257 Practical Collection pbootcmstemplate

This set of adaptive mobile-responsive SEO tutorials and news-based PbootCMS website templates features a clean, informative design, making it ideal for SEO bloggers to share optimization tips, industry trends, and case studies. It helps SEO professionals build their personal brands and establish knowledge influence online. Template preview | Installation instructions | Website backend: /admin.php | Account: admin | Password: admin | Unzip password: www.4s5....
👁 307
Blue mini program website pbootcms template-mini program e-commerce software development company website source code (pc+wap) 0453

Blue mini program website pbootcms template-mini program e-commerce software development company website source code (pc+wap) 0453 Practical Collection pbootcmstemplate

This set of adaptive mobile hardware accessories and machining equipment is presented as a PbootCMS website template. The design is professional and practical, enabling the display of hardware components, machining services, and product specifications. It helps hardware accessory companies showcase their production capabilities online and attract manufacturing clients. Template display; installation instructions; website backend: /admin.php; account: admin; password: admin; extraction password: www.4s5.cn...
👁 267
(Adaptive mobile phone version) High-end luxury watch website pbootcms template Responsive luxury watch website source code download 0825

(Adaptive mobile phone version) High-end luxury watch website pbootcms template Responsive luxury watch website source code download 0825 Practical Collection pbootcmstemplate

A high-end luxury watch and luxury timepiece PbootCMS responsive website template that supports both PC and WAP devices. Featuring a sophisticated and luxurious design, it is ideal for showcasing luxury watch products, brand narratives, and exquisite craftsmanship. It helps luxury brands communicate their brand value online and attract high-net-worth customers. Template showcase | Installation instructions | Website backend: /admin.php | Account: admin | Password: admin | Unzip password: www.4s5....
👁 297