Wordpress database insert() 및 update() - NULL 값 사용
워드프레스에는wpdbCRUD 동작을 처리하는 클래스입니다.이 수업의 두 가지 방법에 관심이 있는 두 가지 방법은insert()(CRUD의 C) 및update()(CRUD의 U).
mysql 데이터베이스 컬럼에 NULL을 삽입할 때 문제가 발생합니다.wpdb클래스는 PHP null 변수를 이스케이프하여 문자열을 비웁니다.Wordpress에 실제 MySQL을 사용하도록 지시하려면 어떻게 해야 합니까?NULLMySQL 문자열 대신?
호환성을 유지하려면 SHOW COLUMN을 표시하고 NULL이 허용되는지 확인해야 합니다.허용된 경우 값이 비어 있으면 쿼리에서 val = NULL을 사용합니다.
$foo = null;
$metakey = "Harriet's Adages";
$metavalue = "WordPress' database interface is like Sunday Morning: Easy.";
if ($foo == null) {
$wpdb->query( $wpdb->prepare( "
INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value, field_with_null )
VALUES ( %d, %s, %s, NULL )",
10, $metakey, $metavalue ) );
} else {
$wpdb->query( $wpdb->prepare( "
INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value, field_with_null )
VALUES ( %d, %s, %s, %s)",
10, $metakey, $metavalue, $foo ) );
}
여기 당신의 문제에 대한 해결책이 있습니다."wp-content" 폴더에 "db.php"라는 이름의 파일을 만들고 이 파일에 다음 코드를 넣습니다.
<?php
// setup a dummy wpdb to prevent the default one from being instanciated
$wpdb = new stdclass();
// include the base wpdb class to inherit from
//include ABSPATH . WPINC . "/wp-db.php";
class wpdbfixed extends wpdb
{
function insert($table, $data, $format = null) {
$formats = $format = (array) $format;
$fields = array_keys($data);
$formatted_fields = array();
$real_data = array();
foreach ( $fields as $field ) {
if ($data[$field]===null)
{
$formatted_fields[] = 'NULL';
continue;
}
if ( !empty($format) )
$form = ( $form = array_shift($formats) ) ? $form : $format[0];
elseif ( isset($this->field_types[$field]) )
$form = $this->field_types[$field];
else
$form = '%s';
$formatted_fields[] = "'".$form."'";
$real_data[] = $data[$field];
}
//$sql = "INSERT INTO <code>$table</code> (<code>" . implode( '</code>,<code>', $fields ) . "</code>) VALUES (" . implode( ",", $formatted_fields ) . ")";
$sql = "INSERT INTO $table (" . implode( ',', $fields ) . ") VALUES (" . implode( ",", $formatted_fields ) . ")";
return $this->query( $this->prepare( $sql, $real_data) );
}
function update($table, $data, $where, $format = null, $where_format = null)
{
if ( !is_array( $where ) )
return false;
$formats = $format = (array) $format;
$bits = $wheres = array();
$fields = (array) array_keys($data);
$real_data = array();
foreach ( $fields as $field ) {
if ($data[$field]===null)
{
$bits[] = "$field = NULL";
continue;
}
if ( !empty($format) )
$form = ( $form = array_shift($formats) ) ? $form : $format[0];
elseif ( isset($this->field_types[$field]) )
$form = $this->field_types[$field];
else
$form = '%s';
$bits[] = "$field = {$form}";
$real_data[] = $data[$field];
}
$where_formats = $where_format = (array) $where_format;
$fields = (array) array_keys($where);
foreach ( $fields as $field ) {
if ( !empty($where_format) )
$form = ( $form = array_shift($where_formats) ) ? $form : $where_format[0];
elseif ( isset($this->field_types[$field]) )
$form = $this->field_types[$field];
else
$form = '%s';
$wheres[] = "$field = {$form}";
}
$sql = "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
return $this->query( $this->prepare( $sql, array_merge($real_data, array_values($where))) );
}
}
$wpdb = new wpdbfixed(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
?>
이렇게 하면 wpdb에서 null 값을 사용할 수 있습니다.
Wordpress StackExchange 포럼에서 찾았는데 매우 잘 작동합니다.
// Add a filter to replace the 'NULL' string with NULL
add_filter( 'query', 'wp_db_null_value' );
global $wpdb;
$wpdb->update(
'table',
array(
'status' => 'NULL',
),
array( 'id' => 1 )
);
// Remove the filter again:
remove_filter( 'query', 'wp_db_null_value' );
함수 wp_db_syslog_value는 다음과 같습니다.
/**
* Replace the 'NULL' string with NULL
*
* @param string $query
* @return string $query
*/
function wp_db_null_value( $query )
{
return str_ireplace( "'NULL'", "NULL", $query );
}
제 경우 $db->prepare() 함수를 사용할 수 없기 때문에...
wpdbinsert()그리고.update()와 연동하다NULL값은 수년 전에 패치되었지만 Codex에는 언급되지 않았습니다.
고객님의 경우:
$wpdb->update(
'table',
array(
'status' => null,
),
array( 'id' => 1 ),
null,
'%d'
);
참고 자료: https://core.trac.wordpress.org/ticket/15158#no0
포맷 배열이 데이터 배열과 잘못 정렬되었기 때문에 여기에 나열된 다른 솔루션 중 하나를 편집하려고 했지만 실패했습니다.
다음은 insert() 및 update()를 사용하여 SQL 테이블에 늘 값을 삽입 및 업데이트할 수 있도록 최신 버전의 워드프레스에서 wpdb를 변경하는 솔루션입니다.
/*
* Fix wpdb to allow inserting/updating of null values into tables
*/
class wpdbfixed extends wpdb
{
function insert($table, $data, $format = null) {
$type = 'INSERT';
if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
return false;
$this->insert_id = 0;
$formats = $format = (array) $format;
$fields = array_keys( $data );
$formatted_fields = array();
foreach ( $fields as $field ) {
if ( !empty( $format ) )
$form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
elseif ( isset( $this->field_types[$field] ) )
$form = $this->field_types[$field];
else
$form = '%s';
//***Steve Lee edit begin here***
if ($data[$field]===null) {
unset($data[$field]); //Remove this element from array, so we don't try to insert its value into the %s/%d/%f parts during prepare(). Without this, array would become shifted.
$formatted_fields[] = 'NULL';
} else {
$formatted_fields[] = $form; //Original line of code
}
//***Steve Lee edit ends here***
}
$sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES (" . implode( ",", $formatted_fields ) . ")";
return $this->query( $this->prepare( $sql, $data ) );
}
function update($table, $data, $where, $format = null, $where_format = null)
{
if ( ! is_array( $data ) || ! is_array( $where ) )
return false;
$formats = $format = (array) $format;
$bits = $wheres = array();
foreach ( (array) array_keys( $data ) as $field ) {
if ( !empty( $format ) )
$form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
elseif ( isset($this->field_types[$field]) )
$form = $this->field_types[$field];
else
$form = '%s';
//***Steve Lee edit begin here***
if ($data[$field]===null)
{
unset($data[$field]); //Remove this element from array, so we don't try to insert its value into the %s/%d/%f parts during prepare(). Without this, array would become shifted.
$bits[] = "`$field` = NULL";
} else {
$bits[] = "`$field` = {$form}"; //Original line of code
}
//***Steve Lee edit ends here***
}
$where_formats = $where_format = (array) $where_format;
foreach ( (array) array_keys( $where ) as $field ) {
if ( !empty( $where_format ) )
$form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
elseif ( isset( $this->field_types[$field] ) )
$form = $this->field_types[$field];
else
$form = '%s';
$wheres[] = "`$field` = {$form}";
}
$sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
}
}
global $wpdb_allow_null;
$wpdb_allow_null = new wpdbfixed(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
이 코드를 functions.php와 같이 항상 실행되는 장소에 삽입하고 새로운 글로벌 $wpdb_allowed_null->insert() 및 ->update()를 정상적으로 사용합니다.
Wordpress와 다른 플러그인에서 예상되는 DB 동작을 유지하기 위해 기본 $wpdb를 덮어쓰는 것보다 이 방법을 선호합니다.
언급URL : https://stackoverflow.com/questions/2596962/wordpress-database-insert-and-update-using-null-values
'source' 카테고리의 다른 글
| 데이터베이스 인덱스의 수가 너무 많습니까? (0) | 2023.03.06 |
|---|---|
| OnKeyDown 이벤트가 React의 div에서 작동하지 않음 (0) | 2023.03.06 |
| 각도를 정의할 때 배열 표기법을 사용하는 이유JS 컨트롤러 (0) | 2023.03.06 |
| Oracle SqlPlus - 출력을 파일에 저장하지만 화면에 표시되지 않음 (0) | 2023.03.06 |
| C#의 Json rest api 응답을 해석하는 중 (0) | 2023.03.06 |