《WordPress development techniques #1 – Running custom queries using the ‘wpdb’ class 》一文详细介绍了wordpress数据库类与数据表设计。博主也是wordpress Download Monitor 插件的作者!
平时开发借助于各种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->escape
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.
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->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 );
}