?
Solved

Help with php replace function

Posted on 2011-10-20
5
Medium Priority
?
220 Views
Last Modified: 2012-05-12
I have a php script which uploads the contents of a text file into a database. It is uploading user details, and a problem I'm running into is that some of the records from the 'zip' field sometimes have a - character in them. I need to modify my script to remove all - characters. I could normally do this but the script I'm using is a little complicated and I'm not sure if I'm doing this correctly. I think this is the line I need to modify:

'".escapeAll($user[$i]["company_zip"]!=''?$user[$i]["company_zip"]:$user[$i]["home_zip"])."',

Part of the trick is that the original file has two zip fields, one for home and one for work. I think the above code only chooses one of these.

So how would I modify the above if I wanted it to remove all - from the final value?

I've included the whole page code below if it will help. Thanks!
/*  start here common database functions  ****/

	function Db_Connect($db_server, $db_user, $db_password)
	{
		global $link;
		
		$link=mysql_connect($db_server, $db_user, $db_password) or die(mysql_error().'-Could not connect to server.');		
		if($link)
		{
			$db=mysql_select_db(DB_NAME, $link) or die(mysql_error().'-Could not connect to database.');
		}		
	}
	
	function Db_Close() 
	{
		global $link;
		return mysql_close($link);
	}

	function Select_Qry($fields,$table,$where_clause,$orderby,$type,$startRow, $PageSize)
	{
			global $link;
			$sql_condition="";
			if($where_clause!="")
			{
				$sql_condition.=" WHERE ".$where_clause;
			}
			if($orderby!='')
			{
				$sql_condition.=" ORDER BY ".$orderby;
			}
			if($orderby !='' && $type!='')
			{
				$sql_condition.=" ".$type;
			}
			if($startRow!='' && $PageSize!='')
			{
				$sql_condition.=" LIMIT ".$startRow.",".$PageSize;
			}
			//echo "SELECT ".$fields." FROM ".$table." ".$sql_condition."".'<br>';
			$resCondition = mysql_query("SELECT ".$fields." FROM ".$table." ".$sql_condition."", $link)or die(mysql_error($link)."Error in selectQry() ");
			if(mysql_num_rows($resCondition) > 0)
				{
					$obCondition = mysql_fetch_array($resCondition);
					$fields="";
					$table="";
					$where_clause="";
					$orderby="";
					$type="";
					#print_r($obCondition);
					
					return $obCondition;
				}
			else
			{
					$fields="";
					$table="";
					$where_clause="";
					$orderby="";
					$type="";
				    return false;
			}
	}
		
	function Listing_Qry($field,$table,$where_clause)
	{
		global $link;
		if($where_clause != "")
		{
			//echo "SELECT ".$field." FROM ".$table." ".$where_clause."<br/>";
			$ListContent = mysql_query("SELECT ".$field." FROM ".$table." ".$where_clause."", $link) or die(mysql_error($link)."Error in 			listingQry()");
		}
		else
		{
			$ListContent = mysql_query("SELECT ".$field." FROM ".$table, $link) or die(mysql_error($link)."Error in listingQry()");
		}
		if(mysql_num_rows($ListContent) > 0)
		{
			while($objContent = mysql_fetch_array($ListContent))
			{
				$arrList[] = $objContent;
			}
			return $arrList;
		}
		else
		{
			return 0;
		}
	}

	function Delete_Qry($table,$where_clause)
	{
		global $link;
		mysql_query("DELETE FROM ".$table." ".$where_clause."", $link) or die(mysql_error($link)."Error in deleteQry()");
		//print "DELETE FROM ".$table." ".$where_clause."";
		return true;
	}

	function Insert_Qry($table, $fields, $value)
	{
		global $link;
		//print "INSERT INTO ".$table." ".$fields." VALUES ".$value." ".'<br><br><br><br>';
		//exit;
		mysql_query("INSERT INTO ".$table." ".$fields." VALUES ".$value." ", $link) or die(mysql_error($link)." $table $fields  in insertQry()");
		//return mysql_insert_id();
	}

	function Update_Qry($table, $set_value, $where_clause)
	{
		global $link;
		//print "<br>UPDATE ".$table." SET ".$set_value." ".$where_clause."<br>";
		//exit;
		mysql_query("UPDATE ".$table." SET ".$set_value." ".$where_clause."", $link) or die(mysql_error($link)."Error in updateQry()");
		return true;
	}
	
	function escapeAll($string)
	{
		return mysql_real_escape_string(stripslashes(trim($string)));
	}
	
/*  end of common database functions  ***********/

	function createRandPass($char_no)
	{
		$str     = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		$rand_pass = '';
		
		for($i=0; $i<$char_no;$i++)
		{
			$rand_code  = rand(0,strlen($str)-1);
			$rand_pass  .= $str[$rand_code];
		}
		return $rand_pass;
	}
	
	function createPassword($password)
	{
		$salt = createRandPass(32);
		$crypt= md5($password.$salt);
		
		return $crypt.':'.$salt;
	}

	Db_Connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
	
	
/************  now start working to import the text file into dtabase ************/

	$string = "";
	$handler = fopen("rrcna_members.txt", "r");
	
	while(!feof($handler))
	{
    	$string .= fread($handler, filesize("rrcna_members.txt"));
	}
	fclose($handler);
	
	$row = explode("\n",  $string);
	$key = explode("/,", $row[0]);
	
	for($i=0; $i < count($row); $i++)
	{
		$row[$i] = explode("/,", $row[$i]);
	}
	
	for($i=1; $i < count($row); $i++)
	{
		for($j=0; $j < count($row[$i]); $j++)
		{
			$user[$i-1][$key[$j]] = $row[$i][$j];
			$user[$i-1][$j] = $row[$i][$j];
		}
	}

	/*echo '<pre>';
	
	print_r($user);
	
	echo '</pre>';*/
	
	// strt delete functionality here
	$users_to_delete = Listing_Qry(" `id` ", " `jos_users` ", " WHERE usertype = 'Registered' ");
	for($i=0; $i < count($users_to_delete); $i++)
	{
		$users_to_delete_string .= $users_to_delete[$i]['id'] . ",";
	}
	$users_to_delete_string = rtrim($users_to_delete_string, ',');
	
	if($users_to_delete_string != "")
	{
		$aro_to_delete = Listing_Qry(" `id` ", " `jos_core_acl_aro` ", " WHERE value IN (".$users_to_delete_string.") ");
	}
	
	for($i=0; $i < count($aro_to_delete); $i++)
	{
		$aro_to_delete_string .= $aro_to_delete[$i]['id'] . ",";
	}
	$aro_to_delete_string = rtrim($aro_to_delete_string, ',');
	if($aro_to_delete_string != '')
	{
		Delete_Qry(" jos_core_acl_groups_aro_map ", " WHERE aro_id IN (".$aro_to_delete_string.") ");
		Delete_Qry(" jos_core_acl_aro ", " WHERE id IN (".$aro_to_delete_string.") ");
		
		Delete_Qry(" jos_vm_shopper_vendor_xref ", " WHERE user_id IN (".$users_to_delete_string.") ");
		Delete_Qry(" jos_vm_auth_user_vendor ", " WHERE user_id IN (".$users_to_delete_string.") ");
		//Delete_Qry(" jos_vm_user_info ", " WHERE user_id IN (".$users_to_delete_string.") ");
        Delete_Qry(" jos_vm_user_info ", "");

    }
	Delete_Qry(" jos_users ", " WHERE usertype = 'Registered' ");// delete previously deleted users
	
	// end of delete query
	
	$previous_users = Listing_Qry(" `id` ", " `jos_users` ", " WHERE 1");
	$previous_users_string = '';
	
	for($i=0; $i < count($previous_users); $i++)
	{
		$previous_users_string .= $previous_users[$i]['id'] . ",";
	}
	$previous_users_string = rtrim($previous_users_string, ',');
	
	// now create the query
	$fields = " (`name`, `username`, `email`, `password`, `usertype`, `block`, `sendEmail`, `gid`, `registerDate`, `lastvisitDate`, `activation`, `params`, `person_id`) ";
	$values = "";
	
	// now create the insert query for jos_vm_user_ifo
	$fields_vm = " (`user_info_id`, `address_type`, `address_type_name`, `company`, `last_name`, `first_name`, `phone_1`, `phone_2`, `fax`, `address_1`, `address_2`, `city`, `state`, `country`, `zip`, `user_email`, `cdate`, `mdate`, `perms`, `bank_account_type`, `person_id`) ";
	$values_vm = "";

    $default_nation = "USA" ;
    	
	$_x = 0; // part the query for mysql timeout
	for($i=0; $i < count($user); $i++)
	{
		if($user[$i]["last_name"] == "")
			continue;
		if($user[$i]["name"] == "")
			continue;
		
        //'".escapeAll($user[$i]["company_nation"]!=''?$user[$i]["company_nation"]:$user[$i]["home_nation"])."',
                      
		$values .= " ( '".escapeAll($user[$i]["name"])." ".escapeAll($user[$i]["last_name"])."',
					  '".escapeAll($user[$i]["person_id"])."',
					  '".escapeAll($user[$i]["email"])."',
					  '".createPassword($user[$i]["name"])."',
					  '".escapeAll($user[$i]["usertype"])."',
					  '".escapeAll($user[$i]["block"])."',
					  '".escapeAll($user[$i]["sendEmail"])."',
					  '".escapeAll($user[$i]["gid"])."',
					  '".escapeAll($user[$i]["registerDate"])."',
					  '".escapeAll($user[$i]["lastvisitDate"])."',
					  '',
					  '".escapeAll($user[$i]["params"])."',
					  '".escapeAll($user[$i]["person_id"])."' ),";
					  
		$values_vm .= " ( '".escapeAll(md5($user[$i]["person_id"]))."',
					  'BT',
					  '-default-',
					  '".escapeAll($user[$i]["company_name"])."',
					  '".escapeAll($user[$i]["last_name"])."',
					  '".escapeAll($user[$i]["name"])."',
					  '".escapeAll($user[$i]["work_phone1"] . ' ' . $user[$i]["phone_ext"])."',
					  '".escapeAll($user[$i]["home_phone"])."',
					  '".escapeAll($user[$i]["fax_number"])."',
					  '".escapeAll($user[$i]["company_addr1"]!=''?$user[$i]["company_addr1"]:$user[$i]["home_addr1"])."',
					  '".escapeAll($user[$i]["company_addr2"]!=''?$user[$i]["company_addr2"]:$user[$i]["home_addr2"])."',
					  '".escapeAll($user[$i]["company_city"]!=''?$user[$i]["company_city"]:$user[$i]["home_city"])."',
					  '".escapeAll($user[$i]["company_state"]!=''?$user[$i]["company_state"]:$user[$i]["home_state"])."',
					  '".escapeAll($user[$i]["company_nation"]!=''?$user[$i]["company_nation"]:$default_nation)."',
					  '".escapeAll($user[$i]["company_zip"]!=''?$user[$i]["company_zip"]:$user[$i]["home_zip"])."',
					  '".escapeAll($user[$i]["email"])."',
					  '".escapeAll(strtotime($user[$i]["date_dues_paid"]))."',
					  '".escapeAll(time())."',
					  'shopper',
					  'Checking',
					  '".escapeAll($user[$i]["person_id"])."' ),";
					
		
		if($_x==999)
		{
			$values = rtrim($values, ",");
			$values .= ";";
			Insert_Qry(" `jos_users` ", $fields, $values);
			$values = "";
			
			$values_vm = rtrim($values_vm, ",");
			$values_vm .= ";";
			Insert_Qry(" `jos_vm_user_info` ", $fields_vm, $values_vm);
			$values_vm = "";
			
			$_x=0;
		}
		$_x++;
	}
	
	if($values != "")
	{
		$values = rtrim($values, ",");	
		$values .= ";";
		Insert_Qry(" `jos_users` ", $fields, $values);
	}
	
	if($values_vm != "")
	{
		$values_vm = rtrim($values_vm, ",");	
		$values_vm .= ";";
		Insert_Qry(" `jos_vm_user_info` ", $fields_vm, $values_vm);
	}
	
	// now update two tables
	mysql_query(" UPDATE jos_users, jos_vm_user_info SET jos_vm_user_info.user_id = jos_users.id WHERE jos_users.person_id = jos_vm_user_info.person_id AND jos_vm_user_info.person_id != '0' ", $link) or die(mysql_error($link)."Error in updateQry()");
	
	if($previous_users_string!="")
	{
		mysql_query("INSERT INTO `jos_core_acl_aro` ( `value`, `name`) SELECT `id`, `name` FROM `jos_users` WHERE `id` NOT IN(".$previous_users_string.") ", $link) or die(mysql_error($link)."Error in insertQry()");
		Update_Qry(" `jos_core_acl_aro` ", " `section_value` = 'users' ", " WHERE `section_value` = '0'");
		
		mysql_query("INSERT INTO `jos_core_acl_groups_aro_map` ( `group_id`, `aro_id`) SELECT ju.gid, ja.id FROM `jos_users` ju, `jos_core_acl_aro` ja WHERE ju.id = ja.value AND ju.id NOT IN(".$previous_users_string.") ", $link) or die(mysql_error($link)."Error in insertQry()");
		
		mysql_query("INSERT INTO `jos_vm_auth_user_vendor` ( `user_id` ) SELECT `id` FROM `jos_users` WHERE `id` NOT IN(".$previous_users_string.") ", $link) or die(mysql_error($link)."Error in insertQry()");
		Update_Qry(" `jos_vm_auth_user_vendor` ", " `vendor_id` = '1' ", " WHERE `user_id` NOT IN(".$previous_users_string.") ");
		
		mysql_query("INSERT INTO `jos_vm_shopper_vendor_xref` ( `user_id`, `customer_number` ) SELECT `id`, MD5(`id`) FROM `jos_users` WHERE `id` NOT IN(".$previous_users_string.") ", $link) or die(mysql_error($link)."Error in insertQry()");
		Update_Qry(" `jos_vm_shopper_vendor_xref` ", " `vendor_id` = '1', `shopper_group_id` = '8' ", " WHERE `user_id` NOT IN(".$previous_users_string.") ");
		
	}
	else
	{
		mysql_query("INSERT INTO `jos_core_acl_aro` ( `value`, `name`) SELECT `id`, `name` FROM `jos_users` WHERE 1 ", $link) or die(mysql_error($link)."Error in insertQry()");
		Update_Qry(" `jos_core_acl_aro` ", " `section_value` = 'users' ", " WHERE `section_value` = '0'");
		
		mysql_query("INSERT INTO `jos_core_acl_groups_aro_map` ( `group_id`, `aro_id`) SELECT ju.gid, ja.id FROM `jos_users` ju, `jos_core_acl_aro` ja WHERE ju.id = ja.value ", $link) or die(mysql_error($link)."Error in insertQry()");
		
		mysql_query("INSERT INTO `jos_vm_auth_user_vendor` ( `user_id` ) SELECT `id` FROM `jos_users` WHERE 1 ", $link) or die(mysql_error($link)."Error in insertQry()");
		Update_Qry(" `jos_vm_auth_user_vendor` ", " `vendor_id` = '1' ", " WHERE 1 ");
		
		mysql_query("INSERT INTO `jos_vm_shopper_vendor_xref` ( `user_id`, `customer_number` ) SELECT `id`, MD5(`id`) FROM `jos_users` WHERE 1 ", $link) or die(mysql_error($link)."Error in insertQry()");
		Update_Qry(" `jos_vm_shopper_vendor_xref` ", " `vendor_id` = '1', `shopper_group_id` = '8' ", " WHERE 1 ");
	}
	
	echo "Data imported successfully!";

?>

Open in new window

0
Comment
Question by:elliottbenzle
  • 2
  • 2
5 Comments
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 37002678
This part looks like a "ternary operator" expression.

escapeAll($user[$i]["company_zip"] != NULL ? $user[$i]["company_zip"] : $user[$i]["home_zip"])."',

It says,
IF $user[$i]["company_zip"] is not NULL,
   use $user[$i]["company_zip"] but if it is NULL
   use $user[$i]["home_zip"]

Right after that statement, add something like this:

$user[$i]["company_zip"] = str_replace('-', NULL, $user[$i]["company_zip"]);


0
 
LVL 4

Author Closing Comment

by:elliottbenzle
ID: 37003178
Thanks for the help. That helped to clear it up.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37003221
Thanks for the points -- glad I could help! ~Ray
0
 
LVL 3

Expert Comment

by:re-searcher
ID: 37003242
Before we tell your solutions, we should be sure why you want do this and is it right way for fixing your problem.

Why you want to remove all dashes - on your code? what's your reason? and what's your vision? explain more please.

if you want to remove all dashes with str_replace, your solution is post #37002678 (Ray's answer).
0
 
LVL 3

Expert Comment

by:re-searcher
ID: 37003267
Sorry for my answer, you accept solution on that time which i trying to send some answer/question...

have a good time.
0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

601 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question