File Splitting & Chained Select Boxes - PHP

AID: 2989
  • Status: Published

1130 points

  • Byrajkumar_pb
  • TypeTips/Tricks
  • Posted on2010-04-29 at 00:06:17
Most of us have gotten stuck at some point in a big project.  As a programmer that isn't a big deal.  But the thing is, we have to re-use some code to reduce the production time and cost.  Alright, so getting a code from Internet and using it would be a nice thing in my opinion.  Here i am going to give you the detailed description on what I've done myself on the time of my PHP project development and I thought it would be helpful for others if I posted the code as a article.

Split a Large File

There could be a situation where you want to split a big file that has 10000's of records which we want to split into files of 100 lines.  Say in my case, I got a file with 2000 mail IDs of the customer and want to split it into files of 200, so that I can send mails for that 200 mail IDs (a limitation of our shared hosting).

So I came up with the following solution:
class filesplit{
    function filesplit(){}
    var $_source = 'file_to-split.txt';
    function Getsource()
    {
        return $this->_source;
    }
    function Setsource($newValue)
    {
        $this->_source = $newValue;
    }
    var $_lines = 250;
    function Getlines()
    {
        return $this->_lines;
    }
    function Setlines($newValue)
    {
        $this->_lines = $newValue;
    }
    var $_path = 'secure/';

    function Getpath()
    {
        return $this->_path;
    }
    function Setpath($newValue)
    {
        $this->_path = $newValue;
    }
    function configure($source = "",$path = "",$lines = "")
    {
        if ($source != "") {
            $this->Setsource($source);
        }
        if ($path!="") {
            $this->Setpath($path);
        }
        if ($lines!="") {
            $this->Setlines($lines);
        }
    }
    // Main function that must be called to split the file

    function run()
    {
        $i=0;
        $j=1;
        $date = date("m-d-y");
        unset($buffer);

        $handle = @fopen ($this->Getsource(), "r");
        while (!feof ($handle))
        {
            $buffer .= @fgets($handle, 4096);
            $i++;
            //if ($i >= $split)
            if ($i >= $this->_lines || feof($handle))
            {
                $fname = $this->Getpath()."part.$date".time()."$j.txt";
                if (!$fhandle = @fopen($fname, 'w'))
                {
                    print "Cannot open file ($fname)";
                    exit;
                }

                if (!@fwrite($fhandle, $buffer))
                {
                    print "Cannot write to file ($fname)";
                    exit;
                }
                fclose($fhandle);
                $j++;
                unset($buffer,$i);
            }
        }
        fclose ($handle);
    }
} ?>
                                    
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:

Select allOpen in new window



Here is the sample page to invoke the function:
require_once("filesplit.php"); // Name of the above PHP file
/**
* Sample usage of the filesplit class
**/
$s = new filesplit;
$filename = basename( $_FILES['uploaded']['name']) ;

$s->configure($filename, "secure/", 250);
$s->run();
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window



Chained Combo Box

Another one was PHP/MySQL/Ajax Chained Combo Box.

Every one of us has reached the scenario where the values of combo box need to be changed depending upon the previous combo box selection.

It's been easier if we include Ajax in this as it just deprecated the page loading for such simple thing. Ok, let's have a look at the code:

index.php
<?php
// CONNECT TO DATABASE
include('dbcommon.php');
// IF FORM SUBMITTED ECHO POSTED VALUES
if(isset($_POST['submit'])) {
	echo 'You submitted the form with the following values:<br />Category ID: '.$_POST['catName'].'<br />Product ID: '.$_POST['text'];
}
?>

<html>
<head>
<title>AJAX/PHP/MySQL Chained Select</title>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
var ajax = new Array();
function getTextList(sel) {
	var catName = sel.options[sel.selectedIndex].value;
	document.getElementById('text').options.length = 0;
	if(catName.length>0){
		var index = ajax.length;
		ajax[index] = new sack();
		ajax[index].requestFile = 'getText.php?catID='+catName;
		ajax[index].onCompletion = function(){ createText(index) };
		ajax[index].runAJAX();
	}
}
function createText(index) {
	var obj = document.getElementById('text');
	eval(ajax[index].response);	
}	
</script>
</head>
<body>
<form action="index.php" method="post">
<select id="catName" name="catName" onchange="getTextList(this)">
	<option value="">Select a Category</option>
	<?php
		// QUERY DATABASE TO GET CATEGORIES
		$query = mysql_query("SELECT catID, catName FROM tblcategories ORDER BY catName ASC") or die(mysql_error());
		// LOOP THROUGH ROWS RETURNED TO CREATE SELECT BOX
		while($row = mysql_fetch_array($query)) {
			echo '<option value="'.$row['catID'].'">'.$row['catName'].'</option>';
		}
	?>
</select>
<select id="text" name="text"></select>
<input type="submit" name="submit" value="Submit" />	
</form>
</p>
</body>
</html>
                                    
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:

Select allOpen in new window



getText.php
<?php
// CONNECT TO DATABASE
include('dbcommon.php');
// SET VARIABLES GET VALUES
$catID = $_GET['catID'];
if(isset($_GET['catID'])) {
	// QUERY DATABASE TO GET PRODUCTS DELIMITED BY CATEGORY CHOSEN
	$query = mysql_query("SELECT * FROM tblproduct WHERE catID='$catID'") or die(mysql_error());
	// LOOP THROUGH ROWS RETURNED TO CREATE SELECT BOX
	while($text = mysql_fetch_array($query)) {
		echo 'obj.options[obj.options.length] = new Option("'.$text['prodName'].'","'.$text['prodID'].'");';
	} 
}
?>
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window



dbcommon.php (simple file which has all the MySQL connection details)

<?php
// DATABASE CONNECTION DETAILS
$dbHost = "localhost";
$dbUser = "YOUR_USERNAME";
$dbPass = "YOUR_PASSWORD";
$dbName = "YOUR_DATABASE";
$db = mysql_connect($dbHost,$dbUser,$dbPass);
mysql_select_db($dbName,$db

?>
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window



ajax.js, the magic file which is responsible for the chained combo box functionality
function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	        this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

        	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
		if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
	}
	};
	this.setVar = function(name, value){
	this.vars[name] = Array(value, false);
	};
	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
		return Array(encodeURIComponent(name), encodeURIComponent(value));
	} else {
	this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}
	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}
	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}
		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}
		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());
		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}
			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}
	this.runResponse = function() {
		eval(this.response);
	}
	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}
				this.xmlhttp.onreadystatechange = function() {
				switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							if (self.execute) {
								self.runResponse();
							}
							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}
						self.URLString = "";
							break;
					}
				};
				this.xmlhttp.send(this.URLString);
		}
		}
	};
	this.reset();
	this.createAJAX();
}
                                    
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:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:

Select allOpen in new window



Table structure that used in this sample

--
-- Table structure for table `tblcategories`
--
CREATE TABLE `tblcategories` (
  `catID` int(11) unsigned NOT NULL auto_increment,
  `catName` varchar(50) NOT NULL,
  PRIMARY KEY  (`catID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `tblcategories`
--
INSERT INTO `tblcategories` (`catID`, `catName`) VALUES
(1, 'Category 1'),
(2, 'Category 2'),
(3, 'Category 3'),
(4, 'Category 4');

-- --------------------------------------------------------
-
-- Table structure for table `tblproduct`
--
CREATE TABLE `tblproduct` (
  `prodID` int(11) unsigned NOT NULL auto_increment,
  `catID` int(11) NOT NULL,
  `prodName` varchar(50) NOT NULL,
  PRIMARY KEY  (`prodID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

-
-- Dumping data for table `tblproduct`
--
INSERT INTO `tblproduct` (`prodID`, `catID`, `prodName`) VALUES
(1, 1, 'Product 1'),
(2, 1, 'Product 2'),
(3, 2, 'Product 3'),
(4, 1, 'Product 4'),
(5, 3, 'Product 5'),
(6, 4, 'Product 6'),
(7, 2, 'Product 7'),
(8, 3, 'Product 8'),
(9, 4, 'Product 9'),
(10, 4, 'Product 10');
                                    
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:

Select allOpen in new window



That's it. You're good to go. This approach is much cleaner instead of using plain PHP/MySQL.

Sometimes it looks like PHP/MySQL will be OK for a task, but after going for some time, you feel awkward afterward.  So instead, separate things and give some of them to Ajax so that it'll take care of best part of the functionality with ease.

The easiest way for you to run this code is, simply copy all code to corresponding files and create the table.  Open the index.php file, that's it.
Asked On
2010-04-29 at 00:06:17ID2989
Tags

php file splitting

Topic

PHP Scripting Language

Views
626

Comments

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top PHP Experts

  1. Ray_Paseur

    1,354,218

    Genius

    3,734 points yesterday

    Profile
    Rank: Savant
  2. DaveBaldwin

    284,951

    Guru

    4,300 points yesterday

    Profile
    Rank: Genius
  3. StingRaY

    144,754

    Master

    4,000 points yesterday

    Profile
    Rank: Wizard
  4. jason1178

    143,172

    Master

    1,000 points yesterday

    Profile
    Rank: Genius
  5. bportlock

    123,643

    Master

    1,600 points yesterday

    Profile
    Rank: Genius
  6. ChrisStanyon

    111,336

    Master

    0 points yesterday

    Profile
    Rank: Sage
  7. Roads_Roads

    106,350

    Master

    0 points yesterday

    Profile
    Rank: Genius
  8. maeltar

    95,247

    Master

    0 points yesterday

    Profile
    Rank: Guru
  9. gr8gonzo

    95,168

    Master

    0 points yesterday

    Profile
    Rank: Sage
  10. smadeira

    82,088

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  11. Slick812

    77,062

    Master

    0 points yesterday

    Profile
    Rank: Sage
  12. johanntagle

    74,700

    Master

    2,000 points yesterday

    Profile
    Rank: Sage
  13. logudotcom

    67,088

    Master

    0 points yesterday

    Profile
    Rank: Genius
  14. COBOLdinosaur

    65,841

    Master

    0 points yesterday

    Profile
    Rank: Genius
  15. leakim971

    63,819

    Master

    0 points yesterday

    Profile
    Rank: Genius
  16. un1x86

    56,406

    Master

    0 points yesterday

    Profile
    Rank: Master
  17. Derokorian

    46,763

    10 points yesterday

    Profile
    Rank: Guru
  18. marqusG

    44,475

    10 points yesterday

    Profile
    Rank: Sage
  19. DrDamnit

    42,892

    0 points yesterday

    Profile
    Rank: Genius
  20. ahoffmann

    40,068

    0 points yesterday

    Profile
    Rank: Genius
  21. designatedinitializer

    37,800

    0 points yesterday

    Profile
    Rank: Master
  22. maestropsm

    37,678

    0 points yesterday

    Profile
    Rank: Guru
  23. TerryAtOpus

    34,800

    0 points yesterday

    Profile
    Rank: Genius
  24. xterm

    32,850

    0 points yesterday

    Profile
    Rank: Sage
  25. kaufmed

    31,808

    0 points yesterday

    Profile
    Rank: Genius

Hall Of Fame