一個項目需求要幾百台電腦都有打印功能,本來是想用網絡打印機的,後來發現沒有網絡打印機,就自己動手寫一個打印類算了。
類實現想法是:先把要打印的數據都收集起來,在用js調用window打印函數。目前就使用於IE。
類提供打印排隊功能。(PS,說白了就是一條一條讀取數據)
class Wprint{ //收集打印代碼 private $data = array(); //處理打印代碼 private $handle; public function __construct() { header("Content-type:text/html;charsetutf-8"); $this->link(); //鏈接數據庫 $this->collect($_POST["username"],$_POST["content"],$_POST["ip"]); $this->handle(); } //鏈接數據庫 private function link() { $link = mysql_connect('localhost', 'root', '123456'); mysql_select_db('shen', $link); mysql_query('SET NAMES utf8'); } //收集打印代碼 private function collect($username,$content,$ip) { $code["username"] = $username; $code["content"] = $this->check($content); $code["ip"] = $ip; $code["state"] = 0; $code["priority"] = 0; array_push($this->data,$code);//數據節點入棧 } //處理打印代碼入庫 private function handle() { foreach($this->data as $value) { $sql = "insert into print(username,content,ip,state,priority) values('{$value["username"]}','{$value["content"]}', '{$value["ip"]}','{$value["state"]}','{$value["priority"]}')"; $query = mysql_query($sql); if($query) { $id = mysql_insert_id(); //獲取最近insert操作得到的ID echo "數據收集成功,正在排隊打印,排隊ID為".$id; $this->num($id); } else { echo "數據收集失敗,請3秒後再一次提交"; } } } //檢查傳人數據是否為空 private function check($string) { if(strlen($string) == 0 || $string == " ") { echo "數據收集失敗,打印內容為空"; exit; }else { return $string; } } //獲取打印排隊人數 private function num($id) { $sql = "select id from print where state=0 and id<".$id." order by id asc"; $query = mysql_query($sql); $num = mysql_num_rows($query); echo ",您前面還有".$num."個人在排隊"; } //打印數據 public function Yprint() { $sql = "select id,content from print where state=0 order by id asc limit 1"; $query = mysql_query($sql); $row = mysql_fetch_array($query); if(!empty($row["content"])) { echo "<script tyle=\"text/javascript\"> window.print(); </script>"; $id = $row["id"]; $sql = "update print set state=1 where id=".$id; mysql_query($sql); echo "打印處理完成"; }else { echo $row["content"]; } } }
思想很簡單,收集數據再一個一個處理。 這樣就不僅解決了網絡打印的問題,還避免了網絡打印打印過程排隊的問題。