<

File Splitting & Chained Select Boxes - PHP

Published on
8,921 Points
2,921 Views
Last Modified:
Approved
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);
    }
} ?>

Open 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();

Open 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>

Open 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'].'");';
	} 
}
?>

Open 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

?>

Open 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();
}

Open 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');

Open 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.
0
Comment
Author:rajkumar_pb
0 Comments

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Join & Write a Comment

The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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 …

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month