Hongmu Notes
Home Program Notes WordPress database query operations
Program Notes wordpress

WordPress database query operations

WordPress database query operations

First, connect to the database.

To connect to a WordPress database, you need to include the relevant code in your PHP file.wp-config.phpFile: This file contains database configuration information for WordPress installation and other constants.

Here is a simple example demonstrating how to introduce it.wp-config.phpRead the file and establish a 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 (e.g.DB_HOSTDB_NAMEDB_USERDB_PASSWORD) To establish a PDO database connection. The PDO (PHP Data Object) library is used here to connect to the database; however, you can also use other libraries or functions for database connection – for specific methods, please refer to the relevant documentation or tutorials.

For Your Attention,wp-config.phpThe file contains sensitive database information, such as database usernames and passwords; therefore, when deploying the website, ensure the security of this file—for example, by placing it in a directory that the web server cannot access directly.

Execute SQL operations

Once introducedwp-config.phpOnce you have the file and obtained a database connection, you can use the functions provided by WordPress to perform database operations. Below is a simple example demonstrating how to query the database.wp_postsAll article titles in the table:

 隐藏内容:登录后可查看
// 引入 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.phpOpen the document and then use it.PDOAcquire a database connection from the database. Then, we use it.$dbh->query()The function executes an SQL query and saves the results into a PDOStatement object. Finally, we use aforeachIterate through the result set and output the title of each article.

Note: The query statement here useswp_postsThe table name; this is because WordPress adds a prefix when creating database tables (the default iswp_This helps distinguish between different WordPress installations. Therefore, if you used a different prefix during the WordPress installation, the table name in the query statement should also be adjusted accordingly.

It is important to note that when performing database queries, care should be taken to prevent SQL injection attacks; therefore, appropriate measures should be taken.$dbh->prepare()The function prepares a secure SQL query and uses bound parameters to prevent input data from being misinterpreted as SQL code. For example:

 隐藏内容:登录后可查看
$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, then uses it.$query->bindParam()Bind input parameters to functions. This ensures that queries are secure and prevents input parameters from being misinterpreted 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 wordpress redis changes the password?

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

Problem description: My wordpress site server uses pagoda panel, installed php8.0, and installed redis on the extension panel, and installed Redis Object Cache plug-in in wordpress. In fact, in general, you don't need to do anything, just start it directly. However, it is unsafe for radis not to set a password, which is a risky loophole, so I still think it is better to set a password, …
👁 255
How do I disable revisions and automatic draft saving in WordPress?

How do I disable revisions and automatic draft saving in WordPress? Program Notes wordpress

WordPress's automatic article revision tracking feature logs every time you edit an article in the后台; each revision is recorded as a separate entry in the `wp_posts` table. Due to the interplay between article revisions and automatic saving, the article ID often grows larger over time. While this typically does not cause significant issues for your WordPress installation, an excessive number of article versions can place a considerable burden on your storage space and database...
👁 373
Detailed Tutorial on Migrating EmpireCMS Blog Data to WordPress

Detailed Tutorial on Migrating EmpireCMS Blog Data to WordPress Program Notes wordpress

PS1: Second revision – now supports data transfer between categories, posts, and tags. PS2: If the post IDs consistently don't match, you can try clearing the WordPress post category data table and relationship tables. I previously used Typecho for my blog, but later migrated to Empire; however, Empire has too many features – using it for a blog feels like putting a large hammer into a small hole! Additionally, I often record important code snippets in my blog – all of which I've painstakingly written...
👁 546
WordPress issue: pages freezing due to image transcoding

WordPress issue: pages freezing due to image transcoding Program Notes wordpress

Last night, while uploading an image, for some reason, the uploaded image was automatically transcoded. Transcoding type: BASE64 encoding. For an image on a website, simply upload it to your server and then access the link – the image will then be displayed. However, there is another approach: directly transcoding the image; then you can simply access the converted image using its encoded URL. Problem description: When an image is relatively small (e.g., only a few KB in size), transcoding it and then hosting it on a website can help avoid...
👁 152
WordPress MySQL Database Table and Subtable Structure Functionality Guide

WordPress MySQL Database Table and Subtable Structure Functionality Guide Program Notes wordpress

WordPress uses a MySQL database. Its data table structure differs slightly from that of conventional databases; data can be stored either in the form of standard data tables or as data elements – the latter approach is less intuitive when viewed directly. To become a developer, you must understand the basic structure of the WordPress database and be able to use it within your own plugins or themes to write to or read from the database. I. Data Tables – As of WordPress...
👁 374

Recommended reading

(PC+WAP) Intelligent Electronic System Equipment Website – pbootCMS Template; Download the Blue Universal Enterprise Electronic Technology Website Source Code – 0073

(PC+WAP) Intelligent Electronic System Equipment Website – pbootCMS Template; Download the Blue Universal Enterprise Electronic Technology Website Source Code – 0073 Practical Collection pbootcms Template

A versatile enterprise website template based on PbootCMS, designed for the electronics, smart systems, and electronic devices industry, supporting both PC and WAP devices. Its futuristic design is ideal for showcasing electronic components, smart terminals, and system solutions. This template enables electronics companies to quickly set up their official brand websites online and demonstrate their technical expertise. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin...
👁 37
Real Estate Property Sales Website Template 0811

Real Estate Property Sales Website Template 0811 Practical Collection Yiyou template

An EyouCMS website template designed specifically for real estate and property sales enterprises. Its sophisticated and professional design enables effective presentation of property developments, unit layouts, sales information, and corporate strength. This template helps real estate companies attract homebuyers online and enhance their brand image. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 56
Empire CMS – Download and Promotional Adaptive Dual-Platform Template for the game "Imitating CoolGameNet" – Version 016

Empire CMS – Download and Promotional Adaptive Dual-Platform Template for the game "Imitating CoolGameNet" – Version 016 Practical Collection empire template

I paid a bit of money to obtain this template – it is available for both mobile and PC devices. However, due to the large volume of data (which was stored on Baidu Netdisk), I cleared the existing data and then simply added my own data after downloading the template. Additionally, since the corresponding pseudo-static rule wasn't found for this template online, I adapted the provided IIS rule into an Nginx rule – a task that required some careful effort. Example: Pseudo-static rule 🔒 Hidden content: View after commenting – `rewrite ^([^\....`
👁 349
(Adaptive Mobile Version) Responsive Domestic Service Website Template – Simplified/Traditional Chinese Bilingual – 1009

(Adaptive Mobile Version) Responsive Domestic Service Website Template – Simplified/Traditional Chinese Bilingual – 1009 Practical Collection pbootcms Template

A responsive PbootCMS website template for domestic service businesses, compatible with both PC and WAP devices, and supports both Simplified and Traditional Chinese languages. Its warm and professional design makes it ideal for domestic service companies to showcase their service offerings and brand image across the Taiwan Strait market. This template helps domestic service enterprises attract household customers online. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 66
(PC+WAP) Custom Cable Tray Manufacturing Website – pbootCMS Template; Steel Structure Blue Universal Corporate Website Source Code Download – 0074

(PC+WAP) Custom Cable Tray Manufacturing Website – pbootCMS Template; Steel Structure Blue Universal Corporate Website Source Code Download – 0074 Practical Collection pbootcms Template

This PbootCMS template is ideal for customized cable tray manufacturing and the steel structure industry. It features a blue, versatile corporate design and is compatible with both PC and mobile devices. Its professional and practical design effectively showcases cable tray products, project examples, and technical specifications, helping steel structure or cable tray enterprises efficiently acquire online customers and promote their brands. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin...
👁 53
Responsive Real Estate Sales and Development Website Template 0814

Responsive Real Estate Sales and Development Website Template 0814 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for real estate sales and development enterprises. Its sophisticated and professional design style effectively showcases property developments, sales information, development case studies, and corporate strength. It helps real estate companies attract homebuyers online and enhance their brand image. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 57