visio文本框拆分_文件拆分和链接选择框-PHP

本文介绍了在开发PHP项目时如何分割大文件和实现链式组合框的功能。通过示例代码展示了使用Ajax进行链式选择框操作,以避免页面重新加载,并提倡将部分功能交由Ajax处理,提高用户体验。
摘要由CSDN通过智能技术生成

visio文本框拆分

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.

我们大多数人都陷于某个大型项目的某个时刻。 作为程序员,这没什么大不了的。 但问题是,我们必须重用一些代码以减少生产时间和成本。 好吧,所以我认为从Internet获取代码并使用它是一件好事。 在这里,我将为您提供有关我在开发PHP项目时所做的工作的详细说明,如果我将代码作为文章发布,我认为这对其他人会有所帮助。

分割大文件
(Split a Large File
)

在某些情况下,您可能希望拆分一个包含10000条记录的大文件,而我们希望将其拆分为100行的文件。 以我的情况为例,我得到了一个包含2000个客户邮件ID的文件,并希望将其拆分为200个文件,以便我可以使用该200个邮件ID发送邮件(这是我们共享主机的限制)。

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);
    }
} ?>

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

链式组合框
(Chained Combo Box
)

另一个是PHP / MySQL / Ajax链式组合框。

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:

如果我们在其中包含Ajax会更容易,因为它不赞成这种简单的页面加载。 好的,让我们看一下代码:

index.php

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>

getText.php

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

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

dbcommon.php(包含所有MySQL连接详细信息的简单文件)

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

?>

ajax.js, the magic file which is responsible for the chained combo box functionality

ajax.js,负责链接组合框功能的魔术文件

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

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

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

而已。 你很好。 这种方法比使用普通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.

有时候,看起来PHP / MySQL可以完成某项任务,但是经过一段时间后,您会觉得很尴尬。 因此,取而代之的是分离事物并将其中一些交给Ajax,这样它就可以轻松处理功能的最佳部分。

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.

运行此代码的最简单方法是,只需将所有代码复制到相应的文件并创建表。 打开index.php文件,就是这样。

翻译自: https://www.experts-exchange.com/articles/2989/File-Splitting-Chained-Select-Boxes-PHP.html

visio文本框拆分

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值