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:
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:
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.