Magento : Issue Category name is auto renaming while saving - php

i am importing the products with advance data flow profile and facing the weird problem while saving the category as i am passing the category name to my function as
Parent Category/Child category
The / sign between categories automatically create and assign the product to child category
it is working as expected but in my case the Parent Category name is renaming somehow i have checked that i am passing the right name to the function...
e.g. Semipreciuos gem stone beads/Stone type is saving as Semipreciuos gem stone bead/Stone type
The last s word is missing from the name
protected function _addCategories($categories,$desc='',$discountable,$store) {
$rootId = $store->getRootCategoryId ();
if (! $rootId) {
return array();
}
$rootPath = '1/' . $rootId;
if (empty ( $this->_categoryCache [$store->getId ()] )) {
$collection = Mage::getModel ( 'catalog/category' )->getCollection ()->setStore($store)->addAttributeToSelect ( 'name' );
$collection->getSelect ()->where ( "path like '" . $rootPath . "/%'" );
foreach ( $collection as $cat ) {
$pathArr = explode ( '/', $cat->getPath () );
$namePath = '';
for($i = 2, $l = sizeof ( $pathArr ); $i < $l; $i ++) {
$name = $collection->getItemById ( $pathArr [$i] )->getName ();
$namePath .= (empty ( $namePath ) ? '' : '/') . trim ( $name );
}
$cat->setNamePath ( $namePath );
}
$cache = array();
foreach ( $collection as $cat ) {
$cache [strtolower ( $cat->getNamePath () )] = $cat;
$cat->unsNamePath ();
}
$this->_categoryCache [$store->getId ()] = $cache;
}
$cache = & $this->_categoryCache [$store->getId ()];
$catIds = array();
foreach ( explode ( ',', $categories ) as $categoryPathStr ) {
$categoryPathStr = preg_replace ( '#s*/s*#', '/', trim ( $categoryPathStr ) );
if (! empty ( $cache [$categoryPathStr] )) {
$catIds [] = $cache [$categoryPathStr]->getId ();
continue;
}
$path = $rootPath;
$namePath = '';
foreach ( explode ( '/', $categoryPathStr ) as $catName ) {
$namePath .= (empty ( $namePath ) ? '' : '/') . strtolower ( $catName );
if (empty ( $cache [$namePath] )) {
$cat = Mage::getModel('catalog/category')->setStoreId($store->getId())->setPath ( $path )->setName ( $catName )->// comment out the following line if new categories should stay inactive
setIsActive(1)->setDescription($desc)->setData('discountable',$discountable)->save();
$cache [$namePath] = $cat;
}
$catId = $cache [$namePath]->getId ();
$path .= '/' . $catId;
}
##Assigning product to child category
/*$parentId = null;
$currentcat = Mage::getModel("catalog/category")->load($catId);
$parentId = $currentcat->getParentId();
if($parentId){
$catIds[] = $parentId;
}
*/
if ($catId) {
$catIds [] = $catId;
}
}
return join ( ',', $catIds );
}
Above is my category function for creating categories... any one has any idea what is going on..

It is not related to Magento, but rather to PHP & regular expression.
$categoryPathStr = preg_replace ( '#s*/s*#', '/', trim ( $categoryPathStr ) );
That line replaces "s*/s*" with "/", which is why you have your last s removed. I see no real reason for that preg_replace (?), so just remove that line, or replace it with
$categoryPathStr = trim ( $categoryPathStr );
so that leading/ending white spaces get removed.

Related

PHP : How to fix array_pop and the value 0

I´m trying from various paths to generate a dimensional array.
For that, I´m using the function found here.
My code
function get_dir_content_to_array( string $dir_path, string $dir_filter = null, string $file_filter = null ) {
if( is_dir_empty( $dir_path ) )
return false;
$output = array();
$files = get_subdir_filtered( $dir_path, $dir_filter, $file_filter );
if ( isset( $files ) ) {
foreach ( $files as $name => $object ) {
if ( $object->getFilename() !== "." && $object->getFilename() !== ".." ) {
// Split by the delimiter.
$delimiter = "/";
$name = str_replace( "\\", $delimiter, $name );
$relative_path = str_replace( $dir_path, "", $name );
$a_relative_path = explode( $delimiter, $relative_path );
$path = [ array_pop( $a_relative_path ) ];
foreach ( array_reverse( $a_relative_path ) as $pathPart ) {
$path = [ $pathPart => $path ];
}
// Add it to a temp list.
$paths[] = $path;
}
$output = call_user_func_array( 'array_merge_recursive', $paths );
}
}
return $output;
}
function get_subdir_filtered( $dir_path, $dir_filter, $file_filter ) {
$path = realpath( $dir_path );
$directory = new \RecursiveDirectoryIterator( $path );
$files = null;
if ( ! empty( $dir_filter ) || ! empty( $file_filter ) ) {
if ( ! empty( $dir_filter ) ) {
$filter = new DirnameFilter( $directory, $dir_filter );
}
if ( ! empty( $file_filter ) ) {
$filter = new FilenameFilter( $filter, $file_filter );
}
$files = new \RecursiveIteratorIterator( $filter );
} else {
$files = new \RecursiveIteratorIterator( $directory );
}
return $files;
}
class DirnameFilter extends FilesystemRegexFilter {
// Filter directories against the regex
public function accept() {
return ( ! $this->isDir() || preg_match( $this->regex, $this->getFilename() ) );
}
}
That works except when a folder is named "0"
How can I fixed that ?
Why array_pop skip the value "0" even if it´s a string ?
When json_encode() encodes an array whose keys are sequential integers starting from 0, or the string equivalents of them, it produces a JSON array rather than an object.
You could use the JSON_FORCE_OBJECT flag, but this will then turn the arrays of filenames inside a folder into objects, which you don't want.
What you can do is use a PHP object instead of an array to represent a folder. json_encode() will encode this as an object, even if it has numeric properties.
I think this might do it:
function get_dir_content_to_array( string $dir_path, string $dir_filter = null, string $file_filter = null ) {
if( is_dir_empty( $dir_path ) )
return false;
$output = array();
$files = get_subdir_filtered( $dir_path, $dir_filter, $file_filter );
if ( isset( $files ) ) {
foreach ( $files as $name => $object ) {
if ( $object->getFilename() !== "." && $object->getFilename() !== ".." ) {
// Split by the delimiter.
$delimiter = "/";
$name = str_replace( "\\", $delimiter, $name );
$relative_path = str_replace( $dir_path, "", $name );
$a_relative_path = explode( $delimiter, $relative_path );
$path = [ array_pop( $a_relative_path ) ];
foreach ( array_reverse( $a_relative_path ) as $pathPart ) {
$folder = new StdClass;
$folder->{$pathPart} = $path;
$path = $folder;
}
// Add it to a temp list.
$paths[] = $path;
}
$output = call_user_func_array( 'array_merge_recursive', $paths);
}
}
return $output;
}
I haven't tested it because I don't have the get_subdir_filtered() function. It's possible that array_merge_recursive won't do the correct merge of this. You might need to merge the objects, too. This tutorial contains an implementation of mergeObjectsRecursively that I think should be a useful substitute.
In my case I got this path : update.json and 0/1/0/filename.zip
As #Barmar said, basically, the problem is when I try to convert an array to a json object.
In PHP, an array is in fact, all the time an object so... $arr = [ "0" => [ "1" => ... ] ] for php, is equal to : $arr = [ 0 => [ 1 => ... ] ]. In PHP 7.2.x, each time you will merge objects, The "0" as string key will be cast to 0 as int.
Consequences
1 . with json_encode
echo json_encode( get_dir_content_to_array(...) );
//result = ["update.json",{"1":[["filename.zip"]]}]
2 . with json_encode and JSON_FORCE_OBJECT
echo json_encode( get_dir_content_to_array(...), JSON_FORCE_OBJECT );
//result = {"0":"update.json","1":{"1":{"0":{"0":"filename.zip"}}}}
//I got 1,0,0,filename.zip instead of 0,1,0,filename.zip
3 . Add (string)
$path = [array_pop( $a_relative_path)];
foreach ( array_reverse( $a_relative_path ) as $pathPart ) {
$path = [ (string) $pathPart => $path ];
}
//Same result of 2.
To keep the right order for the path, I found for the moment a hacky solution :
Add underscore before each key
foreach ( array_reverse( $a_relative_path ) as $pathPart ) {
$path = [ "_" . $a_relative_path => $path ];
}
//result = {"0":"update.json", "_0":{"_1":{"_0":{"0":"filenamezip"}}}}
//With a new file path, I got this :
// {"0":"update.json","_toto":{"_foo":{"0":"test.txt"}},"_0":{"_1":{"_0":{"0":"filename.zip"}}}}
This solution is a hack, but I can make a difference between a kee which is a path "_0":{"_1":{"_0" and a key to index a file "0":"filename.zip"

Insert Ads after X paragraph php

Hi im try to use a class to insert adsense blocks after x numbers of paragraph etc.
its works with regular text, but dont works with adsense codes.
the full code is HERE
<?php
namespace keesiemeijer\Insert_Content;
function insert_content( $content, $insert_content = '', $args = array() ) {
$args = array_merge( get_defaults(), (array) $args );
if ( empty( $insert_content ) ) {
return $content;
}
// Validate arguments
$args['parent_element_id'] = trim( (string) $args['parent_element_id'] );
$args['insert_element'] = trim( (string) $args['insert_element'] );
$args['insert_element'] = $args['insert_element'] ? $args['insert_element'] : 'p';
$args['insert_after_p'] = abs( intval( $args['insert_after_p'] ) );
$parent_element = false;
// Content wrapped in the parent HTML element (to be inserted).
$insert_content = "<{$args['insert_element']}>{$insert_content}</{$args['insert_element']}>";
$nodes = new \DOMDocument();
// Load the HTML nodes from the content.
#$nodes->loadHTML( $content );
if ( $args['parent_element_id'] ) {
$parent_element = $nodes->getElementById( $args['parent_element_id'] );
if ( !$parent_element ) {
// Parent element not found.
return $content;
}
// Get all paragraphs from the parent element.
$p = $parent_element->getElementsByTagName( 'p' );
} else {
// Get all paragraphs from the content.
$p = $nodes->getElementsByTagName( 'p' );
}
$insert_nodes = new \DOMDocument();
#$insert_nodes->loadHTML( $insert_content );
$insert_element = $insert_nodes->getElementsByTagName( $args['insert_element'] )->item( 0 );
if ( !$insert_element ) {
return $content;
}
// Get paragraph indexes
$nodelist = get_node_indexes( $p, $args );
// Check if paragraphs are found.
if ( !empty( $nodelist ) ) {
$insert_index = get_item_index( $nodelist, $args );
if ( false === $insert_index ) {
return $content;
}
// Insert content after this (paragraph) node.
$insert_node = $p->item( $insert_index );
// Insert the nodes
insert_content_element( $nodes, $insert_node, $insert_element );
$html = get_HTML( $nodes );
if ( $html ) {
$content = $html;
}
} else {
// No paragraphs found.
if ( (bool) $args['insert_if_no_p'] ) {
if ( $parent_element ) {
// Insert content after parent element.
insert_content_element( $nodes, $parent_element, $insert_element );
$html = get_HTML( $nodes );
if ( $html ) {
$content = $html;
}
} else {
// Add insert content after the content/
$content .= $insert_content;
}
}
}
return $content;
}
/**
* Get default arguments.
*
* #return array Array with default arguments.
*/
function get_defaults() {
return array(
'parent_element_id' => '',
'insert_element' => 'p',
'insert_after_p' => '',
'insert_if_no_p' => true,
'top_level_p_only' => true,
);
}
function get_node_indexes( $nodes, $args ) {
$args = array_merge( get_defaults(), (array) $args );
$nodelist = array();
$length = isset( $nodes->length ) ? $nodes->length : 0;
$parent_id = trim( $args['parent_element_id'] );
for ( $i = 0; $i < $length; ++$i ) {
$nodelist[ $i ] = $i;
$parent = false;
$node = $nodes->item( $i );
if ( $parent_id ) {
if ( $node->parentNode->hasAttribute( 'id' ) ) {
$parent_id_attr = $node->parentNode->getAttribute( 'id' );
$parent = ( $parent_id === $parent_id_attr );
}
} else {
$parent = ( 'body' === $node->parentNode->nodeName );
}
if ( (bool) $args['top_level_p_only'] && !$parent ) {
// Remove nested paragraphs from the list.
unset( $nodelist[ $i ] );
}
}
return array_values( $nodelist );
}
function get_item_index( $nodelist, $args ) {
if ( empty( $nodelist ) ) {
return false;
}
$args = array_merge( get_defaults(), (array) $args );
$count = count( $nodelist );
$insert_index = abs( intval( $args['insert_after_p'] ) );
end( $nodelist );
$last = key( $nodelist );
reset( $nodelist );
if ( !$insert_index ) {
if ( 1 < $count ) {
// More than one paragraph found.
// Get middle position to insert the HTML.
$insert_index = $nodelist[ floor( $count / 2 ) -1 ];
} else {
// One paragraph
$insert_index = $last;
}
} else {
// start counting at 0.
--$insert_index;
--$count;
if ( $insert_index > $count ) {
if ( (bool) $args['insert_if_no_p'] ) {
// insert after last paragraph.
$insert_index = $last;
} else {
return false;
}
}
}
return $nodelist[ $insert_index ];
}
/**
* Insert an element (and it's child elements) in the content.
*
* #param object $nodes DOMNodeList instance containing all nodes.
* #param object $insert_node DOMElement object to insert nodes after
* #param object $insert DOMElement object to insert
* #return void
*/
function insert_content_element( $nodes, $insert_node, $insert_element ) {
$next_sibling = isset( $insert_node->nextSibling ) ? $insert_node->nextSibling : false;
if ( $next_sibling ) {
// get sibling element (exluding text nodes and whitespace).
$next_sibling = nextElementSibling( $insert_node );
}
if ( $next_sibling ) {
// Insert before next sibling.
$next_sibling->parentNode->insertBefore( $nodes->importNode( $insert_element, true ), $next_sibling );
} else {
// Insert as child of parent element.
$insert_node->parentNode->appendChild( $nodes->importNode( $insert_element, true ) );
}
}
function nextElementSibling( $node ) {
while ( $node && ( $node = $node->nextSibling ) ) {
if ( $node instanceof \DOMElement ) {
break;
}
}
return $node;
}
function get_HTML( $nodes ) {
$body_node = $nodes->getElementsByTagName( 'body' )->item( 0 );
if ( $body_node ) {
// Convert nodes from the body element to a string containing HTML.
$content = $nodes->saveHTML( $body_node );
// Remove first body element only.
$replace_count = 1;
return str_replace( array( '<body>', '</body>' ) , array( '', '' ), $content, $replace_count );
}
return '';
}
to call the function
$args = array(
'insert_after_p' => 3, // Insert after the second paragraph
);
echo keesiemeijer\Insert_Content\insert_content($content, $insert_content, $args );

URL dissector that splits up a query string

Ok so basically I am reading through this piece of source code and do not understand the purpose of a specific area.
class URL_Processor
{
private static $urlPath;
private static $urlBits = array();
/*
Gets data from the current URL
#return Void
*/
public function getURLData()
{
$urldata = (isset($_GET['page'])) ? $_GET['page'] : '' ;
self::$urlPath = $urldata;
if( $urldata == '' )
{
self::$urlBits[] = 'home';
self::$urlPath = 'home';
}
else
{
$data = explode( '/', $urldata );
while ( !empty( $data ) && strlen( reset( $data ) ) === 0 )
{
array_shift( $data );
}
while ( !empty( $data ) && strlen( end( $data ) ) === 0)
{
array_pop($data);
}
self::$urlBits = $this->array_trim( $data );
}
}
private function array_trim( $array )
{
while ( ! empty( $array ) && strlen( reset( $array ) ) === 0)
{
array_shift( $array );
}
while ( !empty( $array ) && strlen( end( $array ) ) === 0)
{
array_pop( $array );
}
return $array;
}
}
So basically from my understanding the two while loops with 'array_shift' in the getURLData method empty out the array but according to my logic the second while loop wont even be able to empty anything out because the first while loop already did.
Then the last line of the method getURLData
self::$urlBits = $this->array_trim( $data );
does the same thing but how if the passed in argument is empty already?
Very confused!!!
The first while loop removes all leading elements in the array where their string length is zero, the second one does the same with trailing elements. reset($array) will point to the first, end($array) to the last element.
Why he mushes it through a second time? I don't know.

need help on a piece of code from PHP 5 Social Networking

I'm trying to get more advanced with php and I pick up the book PHP 5 Social Networking by Michael Peacock. While the book seemed to be interesting it didn't however get to involved in the details of the code. The function I'm trying to figure out is,
public function getURLData()
{
$urldata = ( isset( $_GET['page'] ) ) ? $_GET['page'] : '' ;
$this->urlPath = $urldata;
if( $urldata == '' )
{
$this->urlBits[] = '';
$this->urlPath = '';
}
else
{
$data = explode( '/', $urldata );
while ( !empty( $data ) && strlen( reset( $data ) ) === 0 )
{
//NOTES: php array_shift — Shift an element off the beginning of array
array_shift( $data );
}
while ( !empty( $data ) && strlen( end( $data ) ) === 0)
{
array_pop($data);
}
$this->urlBits = $this->array_trim( $data );
}
}
This a part of a larger class and the $_GET['page'] is something like this: relationships/mutual/3. My main question is what is happening in the else section. I think what is happening that it's removing any empty array indexes but I also question that.
Any help would be appreciated.
EDIT: added array_trim function that is also part of the class
private function array_trim( $array )
{
while ( ! empty( $array ) && strlen( reset( $array ) ) === 0)
{
array_shift( $array );
}
while ( !empty( $array ) && strlen( end( $array ) ) === 0)
{
array_pop( $array );
}
return $array;
}
public function getURLData()
{
Gets the 'page', this data can be obtained by $_GET from the url: for instance: http://mysite.com/?page=contact
If 'page' has been set, is assigned to $urldata, else $urldata=''
$urldata = ( isset( $_GET['page'] ) ) ? $_GET['page'] : '' ;
$this->urlPath = $urldata;
if( $urldata == '' )
{
$this->urlBits[] = '';
$this->urlPath = '';
}
else
{
Now is creating an array with all the substrings from $urldata splited by '/'
$data = explode( '/', $urldata );
If the array $data is not empty (otherwise accessing a non-existent element would raise an exception) or the lenght of the first element is equal to 0, then removes the first element from the array.
while ( !empty( $data ) && strlen( reset( $data ) ) === 0 )
{
//NOTES: php array_shift — Shift an element off the beginning of array
array_shift( $data );
}
If the array $data is not empty (otherwise accessing a non-existent element would raise an exception) or the lenght of the last element is equal to 0, then removes the last element from the array.
while ( !empty( $data ) && strlen( end( $data ) ) === 0)
{
array_pop($data);
}
array_trim is a custom function, not sure what does but probably will do some kind of trimming too
$this->urlBits = $this->array_trim( $data );
}
}

Wordpress database insert() and update() - using NULL values

Wordpress ships with the wpdb class which handles CRUD operations. The two methods of this class that I'm interested in are the insert() (the C in CRUD) and update() (the U in CRUD).
A problem arises when I want to insert a NULL into a mysql database column - the wpdb class escapes PHP null variables to empty strings. How can I tell Wordpress to use an actual MySQL NULL instead of a MySQL string?
If you want it to compatible you would have to SHOW COLUMN and determine ahead if NULL is allowed. If it was allowed then if the value was empty($v) use val = NULL in the query.
$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 ) );
}
Here's a solution to your problem. In "wp-content" folder, create a file named "db.php" and put this code in it:
<?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);
?>
In this way you can use null values with wpdb!
I find this on Wordpress StackExchange forum and it works very well for me.
// 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' );
and the function wp_db_null_value is:
/**
* Replace the 'NULL' string with NULL
*
* #param string $query
* #return string $query
*/
function wp_db_null_value( $query )
{
return str_ireplace( "'NULL'", "NULL", $query );
}
Because in my case I cannot use $db->prepare() function...
wpdb insert() and update() works with NULL values, it was patched many years ago but never mentioned in the Codex.
In your case:
$wpdb->update(
'table',
array(
'status' => null,
),
array( 'id' => 1 ),
null,
'%d'
);
Ref: https://core.trac.wordpress.org/ticket/15158#no0
I tried to edit one of the other solutions listed here, because it resulted in the format array being misaligned with the data array, but failed.
Here is a solution that modifies the wpdb from the latest version of wordpress, in order to allow inserting and updating null values into SQL tables using insert() and update():
/*
* 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);
Insert this code into somewhere that always gets run, like your functions.php, and then use your new global $wpdb_allowed_null->insert() and ->update() as normal.
I preferred this method vs. overriding the default $wpdb, in order to preserve the DB behavior that the rest of Wordpress and other plugins will expect.

Categories