Archive for the ‘PHP/MySQL/AJAX’ Category

Copy Magento Category

Since first laying eyes on Magento, the open source eCommerce software, I been impressed by it’s power, flexibility and rigid code structure. But despite Magento’s almost endless list of strengths, it also has some significant weaknesses, that often leave me frustrated and confused. One such weakness is the apparent lack of any functionality in regards to copying products and categories.

I had created a category, with about 10 child categories. Now I just wanted to duplicate that category 5 times, rather than creating another 4 from scratch, each with 10 children (4×10=40 categories!). Rather than spend the next couple of hours adding categories, I knocked together this quick PHP script. Simply pass in the ID of the category you’d like to duplicate, and it will create a copy of the category, along with all of it’s child categories, as deep as they go!

Ideally, this would be a proper Magento module, but I’m just starting out with Magento. Give me 6 months, eh?!

To use the script, simply copy it into a file such as copycat.php in your Magento root directory and call it like so:

http://www.example.com/copycat.php?id=[CATEGORY ID TO COPY]

<?php
 
 
if(!is_numeric($_GET['id']))die('Please specify a category ID');
 
$catId = $_GET['id'];
 
$xml = simplexml_load_file('app/etc/local.xml');
$host = $xml->global->resources->default_setup->connection->host;
$username = $xml->global->resources->default_setup->connection->username;
$password = $xml->global->resources->default_setup->connection->password;
$dbname = $xml->global->resources->default_setup->connection->dbname; 
$res = mysql_pconnect($host, $username, $password);   
mysql_select_db($dbname);
 
 
 
 
$catsDone = 0;
duplicate_entity($catId);
echo $catsDone . ' Categories duplicated.';
 
function duplicate_entity($id, $parent_id = null){
	global $catsDone;
 
 
	// Grab category to copy
	$sql = "SELECT * FROM catalog_category_entity WHERE entity_id = " . $id;
	$query_entity = mysql_query($sql);
 
	$entity = mysql_fetch_object($query_entity);
 
 
	if(!$parent_id)$parent_id = $entity->parent_id;
 
 
 
 
	mysql_query("INSERT INTO catalog_category_entity (entity_type_id, attribute_set_id, parent_id, created_at, updated_at, path, position, level, children_count)
						VALUES ({$entity->entity_type_id}, {$entity->attribute_set_id}, {$parent_id}, NOW(), NOW(), '', {$entity->position}, {$entity->level}, {$entity->children_count})");
	$newEntityId = mysql_insert_id();
 
	$query = mysql_query("SELECT path FROM catalog_category_entity WHERE entity_id = " . $parent_id);
	$parent = mysql_fetch_object($query);
	$path = $parent->path . '/' . $newEntityId;
 
	mysql_query("UPDATE catalog_category_entity SET path='". $path."' WHERE entity_id=". $newEntityId);
 
 
	foreach(array('datetime', 'decimal', 'int', 'text', 'varchar') as $dataType){
		$sql = "SELECT * FROM catalog_category_entity_".$dataType."
				WHERE entity_id=" . $entity->entity_id;
				//die($sql);
		$query = mysql_query($sql);
		while ($value = mysql_fetch_object($query)){
			mysql_query("INSERT INTO catalog_category_entity_".$dataType." (entity_type_id, attribute_id, store_id, entity_id, value)
							VALUES ({$value->entity_type_id}, {$value->attribute_id}, {$value->store_id}, {$newEntityId}, '{$value->value}')");
		}
	}
 
 
	$sql = "SELECT entity_id FROM catalog_category_entity WHERE parent_id = " . $id;
	$query = mysql_query($sql);
 
	while ($entity = mysql_fetch_object($query)){
		duplicate_entity($entity->entity_id, $newEntityId);
	}
	$catsDone++;
}
 
 
 
 
?>

Tags: ,

Basic SQL Injection Tutorial

Since first laying eyes on Magento, the open source eCommerce software, I been impressed by it’s power, flexibility and rigid code structure. But despite Magento’s almost endless list of strengths, it also has some significant weaknesses, that often leave me frustrated and confused. One such weakness is the apparent lack of any functionality in regards to copying products and categories.

I had created a category, with about 10 child categories. Now I just wanted to duplicate that category 5 times, rather than creating another 4 from scratch, each with 10 children (4×10=40 categories!). Rather than spend the next couple of hours adding categories, I knocked together this quick PHP script. Simply pass in the ID of the category you’d like to duplicate, and it will create a copy of the category, along with all of it’s child categories, as deep as they go!

Ideally, this would be a proper Magento module, but I’m just starting out with Magento. Give me 6 months, eh?!

To use the script, simply copy it into a file such as copycat.php in your Magento root directory and call it like so:

http://www.example.com/copycat.php?id=[CATEGORY ID TO COPY]

<?php
 
 
if(!is_numeric($_GET['id']))die('Please specify a category ID');
 
$catId = $_GET['id'];
 
$xml = simplexml_load_file('app/etc/local.xml');
$host = $xml->global->resources->default_setup->connection->host;
$username = $xml->global->resources->default_setup->connection->username;
$password = $xml->global->resources->default_setup->connection->password;
$dbname = $xml->global->resources->default_setup->connection->dbname; 
$res = mysql_pconnect($host, $username, $password);   
mysql_select_db($dbname);
 
 
 
 
$catsDone = 0;
duplicate_entity($catId);
echo $catsDone . ' Categories duplicated.';
 
function duplicate_entity($id, $parent_id = null){
	global $catsDone;
 
 
	// Grab category to copy
	$sql = "SELECT * FROM catalog_category_entity WHERE entity_id = " . $id;
	$query_entity = mysql_query($sql);
 
	$entity = mysql_fetch_object($query_entity);
 
 
	if(!$parent_id)$parent_id = $entity->parent_id;
 
 
 
 
	mysql_query("INSERT INTO catalog_category_entity (entity_type_id, attribute_set_id, parent_id, created_at, updated_at, path, position, level, children_count)
						VALUES ({$entity->entity_type_id}, {$entity->attribute_set_id}, {$parent_id}, NOW(), NOW(), '', {$entity->position}, {$entity->level}, {$entity->children_count})");
	$newEntityId = mysql_insert_id();
 
	$query = mysql_query("SELECT path FROM catalog_category_entity WHERE entity_id = " . $parent_id);
	$parent = mysql_fetch_object($query);
	$path = $parent->path . '/' . $newEntityId;
 
	mysql_query("UPDATE catalog_category_entity SET path='". $path."' WHERE entity_id=". $newEntityId);
 
 
	foreach(array('datetime', 'decimal', 'int', 'text', 'varchar') as $dataType){
		$sql = "SELECT * FROM catalog_category_entity_".$dataType."
				WHERE entity_id=" . $entity->entity_id;
				//die($sql);
		$query = mysql_query($sql);
		while ($value = mysql_fetch_object($query)){
			mysql_query("INSERT INTO catalog_category_entity_".$dataType." (entity_type_id, attribute_id, store_id, entity_id, value)
							VALUES ({$value->entity_type_id}, {$value->attribute_id}, {$value->store_id}, {$newEntityId}, '{$value->value}')");
		}
	}
 
 
	$sql = "SELECT entity_id FROM catalog_category_entity WHERE parent_id = " . $id;
	$query = mysql_query($sql);
 
	while ($entity = mysql_fetch_object($query)){
		duplicate_entity($entity->entity_id, $newEntityId);
	}
	$catsDone++;
}
 
 
 
 
?>

Tags: , ,

Online MD5 Hasher/Cracker

Cloud CrackerIf you’ve ever worked with a PHP/MySQL application which handles user logins, then you will have worked with MD5 Hashes. An MD5 is a one-way encryption algorithm commonly used by web applications to store passwords.
When a new user creates an account, their password is ‘hashed’ using MD5 and the hash is stored along with their username in the database. When they attempt to login in the future, their entered password is hashed and compared to the hash in the database. If they match, they are authenticated. This is great as the password does not have to be visible in the database.

If you forget your admin password when developing an app and haven’t coded a ‘reset your password’ part yet (I always code these boring bits last!) you have 2 choices. You can create a new MD5 hash and replace the one in the database, or you can ‘crack’ the hash to find out your password. But how?

Enter Cloud Cracker, the free online MD5 hasher/cracker. This nifty little tool will take any password and give you it’s MD5 hash. It will also attempt to ‘crack’ an entered hash and show you the plaintext password.

Click Here to check out Cloud Cracker now. and feel free to hit the ‘Digg’ button if you like it.

What is AJAX?

AjaxWhat is AJAX?
If you find yourself asking this question then you’re either new to PHP/Javascript or you have been hiding under a rock for the past three years.
Since around 2006, the term/buzzword ‘AJAX’ has been thrown around like a frisbee in a playground. So what exactly is AJAX?

If you’ve had an auto-suggest bubble pop up as you’re searching, or if you’ve seen form sub-sections magically appear as you choose options, then you have already used AJAX. Slow, static web pages have given way to speedy, animated interfaces with more nifty features.

Some examples of what you can achieve with AJAX include:

  • Auto-suggest popups
  • Form elements appearing/hiding as you complete the form
  • Slider controls
  • Draggable/droppable content

The term AJAX stands for ‘Asynchronous Javascript And XML’. Technically, AJAX is when javascript sends requests back to the server, receives a response in XML and acts upon it. These days though, AJAX is used more of a blanket term of for anything interactive which uses javascript.

If you have been developing PHP and looking to take your applications to the next level of interactivity, then check out some of the nifty AJAX Javascript frameworks out there that do all the hard work for you:

Make Your Phone ‘Kerching’ When You Make A Sale

cash-registerBeing the egotistical git I am, I wanted my phone to make a ‘kerching’ sound each time I made an affiliate sale. Nothing beats dozing off on a lazy Sunday evening and hearing your cash register ring out. Here’s how I made it happen…

First, you need to receive an email each time you make a sale. If your affiliate network will do this, then the first bit is already done. If not, copy the script below into a php file called something likeĀ  ‘xml-to-email.php’ and upload it to your web server. Full instructions are in comments at the top of the file. You will most likely have to change the regex variable to work with your affiliate network’s own feed format.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
 
/* #########################################################
 
Email When You Make a Sale
Developed by Hayden Kibble July 2009
Hayden@HaydenKibble.com
www.HaydenKibble.com
 
Install instructions:
1. Put your affiliate network login and your email details into the variables below
2. You will probably have to edit '$regex_saletime' to match the sale time/date for your paticular aff networks xml feed
2. Upload this file to your web server.
3. Create a file called 'sales.txt' in the same directory as this script and make sure it has read/write permissions
4. Visit the page and it should show a blank page. An email will probably be sent as it picks up all your recent sales
5. Set a cron job up on your web server to run this script every 10 mins or so
6. If you have problems with any of the above, Google is your friend!
 
######################################################### */
 
$base_url = "https://www.affilliate-network.com/myfeed.xml";
$feed_user = "USERNAME-HERE";
$feed_pass = "PASSWORD-HERE";
$regex_saletime = "/<date>(.*)<\/date>/U";
 
$email_from = "from@address.com";
$email_to = "to@address.com";
$email_subject = "You Made a Sale!";
 
// ##### Do Not Edit Below This Line! #####
 
$ch = curl_init();
 
curl_setopt($ch, CURLOPT_URL, $base_url);
 
// Set your login and password for authentication
curl_setopt($ch, CURLOPT_USERPWD, $feed_user . ':' . $feed_pass);
 
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
// get the data and close the session
$data = curl_exec($ch) or die("Error Getting Feed.");
curl_close($ch);
 
$dates = array();
 
preg_match_all($regex_saletime,$data,$dates);
 
// Read previous sales times from database
$fileData = array();
$myFile = "sales.txt";
$fh = fopen($myFile, 'r');
$fileData = fread($fh, filesize($myFile));
fclose($fh);
 
// Split the file into lines
$fileLines = explode("\n",$fileData);
 
$newsale = false;
 
$fh = fopen($myFile, 'a') or die("can't open file");
 
// See if this sale has already been logged. If not, log it and set 'new sale' variable
foreach($dates[1] as $date){
if (!in_array($date,$fileLines)){
$newsale = true;
$sale_time = $date;
fwrite($fh, $date . "\n");
}
}
fclose($fh);
 
if ($newsale){
mail($email_to,$email_subject,"You have made a sale.\nSale Time: ".$sale_time,"From: " . $email_from);
}
 
?>

To test, empty theĀ  sales.txt file you created and run (access) the script. It will see your recent sales have not been logged and fire off the email. Make sure the email does not go to your junk folder.

If you want your computer to play a ‘kerching’ upon making a sale, you can simply set up a rule in Microsoft Outlook to play the sound upon receiving an email with ‘Payment Received’ in the subject. You get the idea.

For those of you who want the full-on portable cash register, continue on to create a gmail account with a difficult to guess name just for these emails. If you share this address anywhere it will get spammed. We do not want this as you will start hearing an awful lot of incorrect kerching’s!

You now need to set your phone up to use your gmail account. Make it check for new emails every 10 mins or so (depending on how often you set your cron job to run the script) and set this kerching wav as your notification sound.

You are now set! When the php script runs intermittently on the cron job, it parses the feed for new sales. When it finds a new sale it sends an email to your phone, which plays a ‘kerching’ sound on receipt!

Dark Dreamweaver Theme

code-colouringIf, like me, you spend all day staring at a Dreamweaver code screen, you may have given thought to your eyesight and the steps you take to preserve it.

After over 10 years of software development, I have finally taken it upon myself to set my IDE background to black. I have tried this a couple of times over the years, but have immediately changed it back due to it looking ‘wierd’. I had just become too accustomed to the colour coding scheme PHP uses and found it extremely difficult to re-adjust.

After a scour on the internet for some sort of ‘theme’, I came across this excellent color scheme.

I’ve now applied this colour scheme to the three PCs I develop on and two weeks down the line I’m really getting used to it. I think it will take another couple of weeks before the colours become second nature to my brain, but it’s worth it in the long run.