---
title: "wordpress 数据库类详解"
author: "muyu"
date: "2010-08-21T12:41:47Z"
tags: []
categories: ["编程语言"]
slug: "wordpress"
draft: false
lastmod: "2010-08-21T12:43:25Z"
id: 743891
url: "https://muyu.iteye.com/blog/743891"
---

《[WordPress development techniques #1 – Running custom queries using the ‘wpdb’ class](http://blue-anvil.com/archives/wordpress-development-techniques-1-running-custom-queries-using-the-wpdb-class/ "WordPress development techniques #1 – Running custom queries using the ‘wpdb’ class") 》一文详细介绍了wordpress数据库类与数据表设计。博主也是wordpress [**Download Monitor**](http://blue-anvil.com/download/?did=1) 插件的作者！

 

平时开发借助于各种PHP框架，用得多了，一旦自己做项目、自己写代码，就容易忽略一些东西------框架替我们做的越多，我们就越退化，写出的代码质量就差很多了。

 

我特别引用一下wordpress关于insert操作的实现：

 

写道

Keeping data safe for insertion

When inserting data into the database, it shoukd always be escaped to stop people hacking your site, wpdb offers a handy little function for doing this – $wpdb-&gt;escape

```
$safe_string = $wpdb->escape($unsafe_string);
```

The above code runs the escape function on an unsafe string, and puts the result into the $safe\_string varible. This can then be inserted into the database using wpdb safely.

 

下面代码摘自wordpress代码文件**wp-includes/wp-db.php** ：

```
	/**
	 * Escapes content for insertion into the database using addslashes(), for security.
	 *
	 * Works on arrays.
	 *
	 * @since 0.71
	 * @param string|array $data to escape
	 * @return string|array escaped as query safe string
	 */
	function escape( $data ) {
		if ( is_array( $data ) ) {
			foreach ( (array) $data as $k => $v ) {
				if ( is_array( $v ) )
					$data[$k] = $this->escape( $v );
				else
					$data[$k] = $this->_weak_escape( $v );
			}
		} else {
			$data = $this->_weak_escape( $data );
		}

		return $data;
	}

	/**
	 * Weak escape, using addslashes()
	 *
	 * @see addslashes()
	 * @since 2.8.0
	 * @access private
	 *
	 * @param string $string
	 * @return string
	 */
	function _weak_escape( $string ) {
		return addslashes( $string );
	}
```