I have an url that contain the word "&key".
The "&key" word can be at the beginning or at the end of our url.
Ex1= http://xxxxx.com?c1=xxx&c2=xxx&c3=xxx&key=xxx&c4=xxx&f1=xxx
Ex2= http://xxxxx.com?c1=xxx&key=xxx&c2=xxx&c3=xxx&c4=xxx&f1=xxx
What I would like to get is all the time the url with the Key element and it's value.
R1: http://xxxxx.com?c1=xxx&c2=xxx&c3=xxx&key=xxx
R2: http://xxxxx.com?c1=xxx&key=xxx
Here is what I have done:
$lp_sp_ad_publisher = "http://xxxxx.com?c1=xxx&c2=xxx&c3=xxx&key=xxxc4=xxxf1=xxx";
$lp_sp_ad_publisher_cut_link = explode("&", $lp_sp_ad_publisher_cut[1]); // tab
$lp_sp_ad_publisher_cut_link_final = $lp_sp_ad_publisher_cut_link[0]; // http://xxxxx.com?c1=xxx
$counter = 1;
// finding &key inside $lp_sp_ad_publisher_cut_link_final
while ((strpos($lp_sp_ad_publisher_cut_link_final, '&key')) !== false);
{
$lp_sp_ad_publisher_cut_link_final .= $lp_sp_ad_publisher_cut_link[$counter];
echo 'counter: ' . $counter . ' link: ' . $lp_sp_ad_publisher_cut_link_final . '<br/>';
$counter++;
}
I'm only looping once all the time. I guess the while loop isn't refreshing with the inside new value. Any solution?
EDIT: Sorry, I misunderstood the question.
This is tricky because the url key and value can be anything, so it might be safer to breakdown the URL using a combination of parse_url() and parse_str(), then put the url back together leaving off the part you don't want. Something like this:
function cut_url( $url='', $key='' )
{
$output = '';
$parts = parse_url( $url );
$query = array();
if( isset( $parts['scheme'] ) )
{
$output .= $parts['scheme'].'://';
}
if( isset( $parts['host'] ) )
{
$output .= $parts['host'];
}
if( isset( $parts['path'] ) )
{
$output .= $parts['path'];
}
if( isset( $parts['query'] ) )
{
$output .= '?';
parse_str( $parts['query'], $query );
}
foreach( $query as $qkey => $qvalue )
{
$output .= $qkey.'='.$qvalue.'&';
if( $qkey == $key ) break;
}
return rtrim( $output, '&' );
}
Usage:
$input = 'https://www.xxxxx.com/test/path/index.php?c1=xxx&c2=xxx&key=xxx&c3=xxx&c4=xxx&f1=xxx';
$output = cut_url( $input, 'key' );
Output:
https://www.xxxxx.com/test/path/index.php?c1=xxx&c2=xxx&key=xxx
If the intention is to always ensure that the parameter key and it's associated value appear at the end of the string, how about something like:
$tmp=array();$key='';
$parts=explode( '&', parse_url( $_SERVER['REQUEST_URI'], PHP_URL_QUERY ) );
foreach( $parts as $pair ) {
list( $param,$value )=explode( '=',$pair );
if( $param=='key' )$key=$pair;
else $tmp[]=$pair;
}
$query = implode( '&', array( implode( '&', $tmp ), $key ) );
echo $query;
or,
parse_str( $_SERVER['QUERY_STRING'], $pieces );
foreach( $pieces as $param => $value ){
if( $param=='key' ) $key=$param.'='.$value;
else $tmp[]=$param.'='.$value;
}
$query = implode( '&', array( implode( '&', $tmp ), $key ) );
update
I'm puzzled that you were "not getting the good result"!
consider the url:
https://localhost/index.php?sort=0&dir=false&tax=23&cost=99&aardvark=creepy&key=banana&tree=large&ac=dc&limit=1000#569f945674935
The above would output:
sort=0&dir=false&tax=23&cost=99&aardvark=creepy&tree=large&ac=dc&limit=1000&key=banana
so the key=banana gets placed last using either method above.
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.
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 );
}
}
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.
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.