下面一个自己开发应用中会常用到的一款数据库操作类代码,下面有两个文件一个是配置文件一个是操作数据库类,最后简单的列举了这个例类的调用方法。
配置文件 config.db.php
代码如下 |
复制代码 |
<?php
$db_config["hostname"] = "localhost"; //服务器地址
$db_config["username"] = "root"; //数据库用户名
$db_config["password"] = "123"; //数据库密码
$db_config["database"] = "test"; //数据库名称
$db_config["charset"] = "utf8";//数据库编码
$db_config["pconnect"] = 1;//开启持久连接
$db_config["log"] = 1;//开启日志
$db_config["logfilepath"] = './';//开启日志
?>
|
数据库操作类
代码如下 |
复制代码 |
<!--?php
Class DB {
private $link_id;
private $handle;
private $is_log;
private $time;
//构造函数
public function __construct() {
$this--->time = $this->microtime_float();
require_once("config.db.php");
$this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]);
$this->is_log = $db_config["log"];
if($this->is_log){
$handle = fopen($db_config["logfilepath"]."dblog.txt", "a+");
$this->handle=$handle;
}
}
//数据库连接
public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0,$charset='utf8') {
if( $pconnect==0 ) {
$this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
if(!$this->link_id){
$this->halt("数据库连接失败");
}
} else {
$this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw);
if(!$this->link_id){
$this->halt("数据库持久连接失败");
}
}
if(select_db($dbname,$this-%3Elink_id">!@mysql_select_db($dbname,$this->link_id)) {
$this->halt('数据库选择失败');
}
@mysql_query("set names ".$charset);
}
//查询
public function query($sql) {
$this->write_log("查询 ".$sql);
$query = mysql_query($sql,$this->link_id);
if(!$query) $this->halt('Query Error: ' . $sql);
return $query;
}
//获取一条记录(MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH)
public function get_one($sql,$result_type = MYSQL_ASSOC) {
$query = $this->query($sql);
$rt =& mysql_fetch_array($query,$result_type);
$this->write_log("获取一条记录 ".$sql);
return $rt;
}
//获取全部记录
public function get_all($sql,$result_type = MYSQL_ASSOC) {
$query = $this->query($sql);
$i = 0;
$rt = array();
while($row =& mysql_fetch_array($query,$result_type)) {
$rt[$i]=$row;
$i++;
}
$this->write_log("获取全部记录 ".$sql);
return $rt;
}
//插入
public function insert($table,$dataArray) {
$field = "";
$value = "";
if( !is_array($dataArray) || count($dataArray)<=0) {
$this->halt('没有要插入的数据');
return false;
}
while(list($key,$val)=each($dataArray)) {
$field .="$key,";
$value .="'$val',";
}
$field = substr( $field,0,-1);
$value = substr( $value,0,-1);
$sql = "insert into $table($field) values($value)";
$this->write_log("插入 ".$sql);
if(!$this->query($sql)) return false;
return true;
}
//更新
public function update( $table,$dataArray,$condition="") {
if( !is_array($dataArray) || count($dataArray)<=0) {
$this->halt('没有要更新的数据');
return false;
}
$value = "";
while( list($key,$val) = each($dataArray))
$value .= "$key = '$val',";
$value .= substr( $value,0,-1);
$sql = "update $table set $value where 1=1 and $condition";
$this->write_log("更新 ".$sql);
if(!$this->query($sql)) return false;
return true;
}
//删除
public function delete( $table,$condition="") {
if( empty($condition) ) {
$this->halt('没有设置删除的条件');
return false;
}
$sql = "delete from $table where 1=1 and $condition";
$this->write_log("删除 ".$sql);
if(!$this->query($sql)) return false;
return true;
}
//返回结果集
public function fetch_array($query, $result_type = MYSQL_ASSOC){
$this->write_log("返回结果集");
return mysql_fetch_array($query, $result_type);
}
//获取记录条数
public function num_rows($results) {
if(!is_bool($results)) {
$num = mysql_num_rows($results);
$this->write_log("获取的记录条数为".$num);
return $num;
} else {
return 0;
}
}
//释放结果集
public function free_result() {
$void = func_get_args();
foreach($void as $query) {
if(is_resource($query) && get_resource_type($query) === 'mysql result') {
return mysql_free_result($query);
}
}
$this->write_log("释放结果集");
}
//获取最后插入的id
public function insert_id() {
$id = mysql_insert_id($this->link_id);
$this->write_log("最后插入的id为".$id);
return $id;
}
//关闭数据库连接
protected function close() {
$this->write_log("已关闭数据库连接");
return @mysql_close($this->link_id);
}
//错误提示
private function halt($msg='') {
$msg .= "\r\n".mysql_error();
$this->write_log($msg);
die($msg);
}
//析构函数
public function __destruct() {
$this->free_result();
$use_time = ($this-> microtime_float())-($this->time);
$this->write_log("完成整个查询任务,所用时间为".$use_time);
if($this->is_log){
fclose($this->handle);
}
}
//写入日志文件
public function write_log($msg=''){
if($this->is_log){
$text = date("Y-m-d H:i:s")." ".$msg."\r\n";
fwrite($this->handle,$text);
}
}
//获取毫秒数
public function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
}
?>
|
使用方法
代码如下 |
复制代码 |
$db = new DB();
调用
$db->insert_id();//获取最新IP地址
|
在网上看到有很多关于截取中文字符串的一些函数,在此本文章就为各位整理一下这些常用的截取中文字符串的例子吧,希望例子能帮助到大家哦。
常用的php函数
strstr(string,string) //从前面第一次出现某个字符串的地方截取到最后
strrchr(string,string) //从某个字符串从最后出现的位置截取到结尾
strpos(string,string[,int]) //某个字符串第一次出现的位置
strrpos(string,string) //某个字符串最后一次出现的位置
substr(string,int[,int]) //从指定位置开始截取字符串,可以指定截取的长度。
strlen(string) //获取字符串的长度PHP截取开始和结束标记间的字符
方法一:利用explode对字符串进行分
代码如下 |
复制代码 |
/**
* Get the content between $start and $end
*
* @param string $content 原始字符
* @param string $start 起始字符
* @param string $end 结束字符
* @return string
*/
function GetStringBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
|
方法二:利用substr截取字符,由于php组件函数,因此字符串处理效率比explode方法要高一些
代码如下 |
复制代码 |
/**
* Get the content between $start and $end
*
* @param string $content 原始字符
* @param string $start 起始字符
* @param string $end 结束字符
* @return string
*/
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
|
PHP截取所有符合起始与结束标记的字符串
代码如下 |
复制代码 |
/**
* Get all every strings between two tags
*
* @param string $string 原始字符串
* @param string $start 起始字符串
* @param string $end 结束字符串
* @return array
*/
function get_all_strings_between($string,$start,$end)
{
//Returns an array of all values which are between two tags in a set of data
$strings = array();
$startPos = 0;
$i = 0;
//echo strlen($string)."n";
while($startPos < strlen($string) && $matched = get_string_between(substr($string,$startPos),$start,$end))
{
if ($matched == null || $matched[1] == null || $matched[1] == '') break;
$startPos = $matched[0]+$startPos+1;
array_push($strings,$matched[1]);
$i++;
}
return $strings;
}
function get_string_between($string, $start, $end){
$ini = strpos($string,$start);
if ($ini == 0) return null;
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return array($ini+$len,substr($string,$ini,$len));
}
|
php截取起始与结束标记间字符,带截取次数、是否允许重复选项
代码如下 |
复制代码 |
/**
* Get all every strings between two tags
*
* @param string $string 原始字符串
* @param string $start 起始字符串
* @param string $end 结束字符串
* @return array
*/
function get_all_strings_between($string,$start,$end)
{
//Returns an array of all values which are between two tags in a set of data
$strings = array();
$startPos = 0;
$i = 0;
//echo strlen($string)."n";
while($startPos < strlen($string) && $matched = get_string_between(substr($string,$startPos),$start,$end))
{
if ($matched == null || $matched[1] == null || $matched[1] == '') break;
$startPos = $matched[0]+$startPos+1;
array_push($strings,$matched[1]);
$i++;
}
return $strings;
}
function get_string_between($string, $start, $end){
$ini = strpos($string,$start);
if ($ini == 0) return null;
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return array($ini+$len,substr($string,$ini,$len));
}
|
截取GB2312中文字符串
代码如下 |
复制代码 |
< ?php
//截取中文字符串
function mysubstr($str, $start, $len) {
$tmpstr = "";
$strlen = $start + $len;
for($i = 0; $i < $strlen; $i++) {
if(ord(substr($str, $i, 1)) > 0xa0) {
$tmpstr .= substr($str, $i, 2);
$i++;
} else
$tmpstr .= substr($str, $i, 1);
}
return $tmpstr;
}
?>
|
截取utf8编码的多字节字符串
代码如下 |
复制代码 |
< ?php
//截取utf8字符串
function utf8Substr($str, $from, $len)
{
return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
'$1',$str);
}
?>
|
静态化页面的好处就不说了,现在我们下文要介绍的实现方法就是利用定义的模板页面和标签然后再利用php读取模板页面之后进入分析替换就可以了,具体我们来看两个例子。
方案:使用模板替换技术(没有时间延迟)
代码如下 |
复制代码 |
/*
|------------------
| <www.111cn.net>
|------------------
*/
$oper = $_POST['oper'];//添加操作
if($oper === 'add')
{
$title = $_POST['title'];
$content = $_POST['content'];
//如果严格按MVC,这里应该调用model了
$con = mysql_connect('localhost', 'root', '123456');
if(!$con)
{
die('连接失败!');
}
mysql_select_db('news', $con);
$sql = "insert into question(null, '$title', '$content', '')";
if(mysql_query($sql, $con))
{
//1.生成静态文件
$id = mysql_insert_id();
$html_filename = 'news-id'.$id.'.html';
$html_fp = fopen($html_filename, 'w');
//2.把模板文件读取(news.html)
$fp = fopen('news.tpl', 'r');
//r 只读方式打开; r+ 读写方式打开; w 写入方式打开:文件内容将被清空!如果文件不存在将创建; a 以追加的方式打开
//3.循环读取
//如果没有读到文件的最后,就一直读取
while(!feof($fp))
{
//一行行读
$row = fgets($fp);
//把占位符替换掉 => 可以自定义完整的替换规则函数
$row = str_replace('%title%', $title, $row);//如果不重新赋值$row, $row值不会改变
$row = str_replace('%content%', $content, $row);
fwrite($html_fp, $row);//4.将内容写入静态文件
}
//5.文件必须关闭
fclose($html_fp);
fclose($fp);
echo "添加成功。<a href='newslist.php'>点击查看新闻!</a>";
}
else
{
die('添加失败!');
}
}
//此时在新闻列表内,点击查看详情的链接,可以改成生成的静态页面地址,直接进入静态文件。
//news.tpl模板文件
/*
<html>
<head>
<meta charset="utf-8" />
<title>%title%</title>
</head>
<body>
<h1>%title%</h1>
<pre>%content%</pre>
</body>
</html>
*/
|
方案:如果静态文件存在,且生成时间30秒内,直接返回静态页面(有时间延迟)
代码如下 |
复制代码 |
/*
|------------------
| <www.111cn.net>
|------------------
*/
header('content-type:text/html;charset=utf-8');
$id = $_GET['id'] ? intval($_GET['id']) : '';
if($id === '') die('请输入要查询的新闻id!');
$html_file = "news-id-".$id.".html";
//1.主要代码
if(file_exists($html_file) && filemtime($html_file) + 30 >= time())
{
echo '静态页面:';
echo file_get_contents($html_file);exit;
}
//这里也可以使用DB工具类
$con = mysql_connect('localhost', 'root', '123456');
if(!$con)
{
die('连接失败!');
}
mysql_select_db('testdb', $con);
$sql = "select * from bo_question where question_id = $id";
$res = mysql_query($sql, $con);
if($row = mysql_fetch_assoc($res))
{
ob_start();//2.启动ob缓存
header('content-type:text/html;charset=utf-8');
echo '<head><meta http-equiv="content-type" content="text/html;charset=utf-8" /></head>';
echo '<table style="border:1px solid red;" cellspacing="0" width="400px" height="200px">';
echo '<tr><td>问题详细内容</td></tr>';
echo "<tr><td>标题:{$row['question_title']}</td></tr>";
echo "<tr><td>详细:{$row['question_detail']}</td></tr>";
echo '</table>';
$ob_str = ob_get_contents();
//3.把ob_str保存到一个静态文件页面,取文件名有讲究:1.唯一标识该新闻 2.利于seo
file_put_contents("news-id-".$id.".html", $ob_str);
//关闭数据库连接(非必须; 非长连接下,脚本执行完会自动关闭)
mysql_close($con);
}else{
echo '没有查询到资源!';
}
|
从上面看我们头一种生成静态页面的方法更合适于页面的后期维护哦,后者是比较难维护的哦,推荐使用第一种办法。
多个文件同时上传到服务器我们需要使用到数组形式的参数传递及数据的遍历上传即可,具体的操作步骤下文来给各位介绍一下吧。
实例说明
上传图片到服务器,是程序开发过程中必不可少的一个功能。它不但可以达到图片共享的目的,而且可以提高网站的访问量,丰富网站的内容。在本实例中,讲解如何通过POST方式实现多图片上传。
关键技术
多文件上传的关键是如何定义上传文件元素的名称及如何判断上传文件的数量。在本实例中,以数组的形式定义上传文件的名称(上传文件的名称是“files[]”)。为了达到可以上传任意数量图片(4个图片以内)的目的,在对上传文件进行处理的过程中应用array_filter()函数和回调函数去除数组中的空元素。
array_filter()函数,用回调函数过滤数组中的单元,语法如下:
array array_filter(array input[,callback callback])
array_filter()函数依次将input数组中的每个值传递到callback函数。如果callback函数返回TRUE,则input数组的当前值会被包含在返回的结果数组中,并且数组的键名保留不变。
说明:在回调函数中不要对数组进行修改操作,例如,增加或者删除数组中的元素,如果一旦数组改变,那么此函数的运用也就没有意义了。如果没有提供callback()函数,array_filter()将删除input中所有等值为FALSE的元素。
本实例中定义的回调函数是check(),用于验证数组中的元素值是否为空,其语法如下:
代码如下 |
复制代码 |
function check($var){//验证数组的返回值是否为空
return($var!="");
}
|
说明:通过POST方法实现多图片上传,在创建form表单时,必须指定enctype="multipart/form-data"属性。如果要通过隐藏域MAX_FILE_SIZE的值对上传文件的大小进行控制,那么必须将隐藏放置在上传文件的文件域之前,否则是不会起作用的。
设计过程
(1)创建index.php文件。添加表单,设置文件域、提交按钮,使用POST方法,设置enctype="multipart/form-data",将数据提交到index_ok.php页,完成多个文件的上传操作,其关键代码如下:
代码如下 |
复制代码 |
<table width="750"border="0"cellspacing="0"cellpadding="0">
<form action="index_ok.html"method="post"enctype="multipart/form-data"name="form1">
<tr>
<td width="100"height="25"align="right"class="STYLE1">内容1:</td>
<td width="150"align="center"><input name="files[]"type="text"id="files[]"size="15"></td>
<td align="left"><input name="picture[]"type="file"id="pcture[]"size>="30"></td>
</tr>
<tr>
<td height="25"align="right"class="STYLE1">内容2:</td>
<td width="center"><input name="files[]"type="text"id="files[]"size="15"></td>
<td align="left"><input name="picture[]"type="file"id="pcture[]"size>="30"></td>
</tr>
<tr>
<td colspan="3"align="center">
<input type="image"name="imageField"src="images/bg_09.jpg">
<input type="image"name="imgeField2"src="images/bg_11.jpg"></td>
</tr>
</form>
</table>
|
(2)在index.php文件中,连接数据库,读取数据库中存储的数据,实现上传文件的分页输出。代码请参考光盘中的相关内容。
(3)创建index.php文件获取表单中提交的数据,将多个文件存储到服务器中,将文件的名称和存储路径存储到数据库中,其代码如下:
代码如下 |
复制代码 |
<?php
header("Content-type:text/html;charset=UTF-8"); //设置文件编码格式
include"conn/conn.php"; //包含数据库链接文件
if($_POST[files]!=""){
if(! is_dir("./upfile")){
mkdir("./upfile");//创建上传文件存储文件夹
}
$data=date("Y-m-d H:m:s");//定义时间
function check($var){ //验证数组的返回值是否为空
return($var!="");//如果不为空则返回数组元素
}
$files=array_filter($_POST["files"],"check");//去除数组中空值
$array=array_filter($_FILES["picture"]["name"],"check"); //去除数组中空值
foreach=($aarray as $key=>value){ //循环读取数组中数据
$path='upfile/'.time().$key.strtolower(strstr($value,".")); //定义上传文件存储位置
move_uploaded_file($_FILES["picture"]["tmp_name"][$key],$path);//执行上传操作
$query="insert into tb_up_file(file_test,data,file_name)values('$path','$data''$files[$key]')";
$result=mysql_query($query);
}
echo"<script>
alert('图片上传成功');window.location.href='index.html';</script>";
}
>?
|
秘笈心法
通过伪静态技术隐藏PHP文件后缀。
首先,修改Apache服务器的配置文件httpd.conf。打开httpd.conf文件,定位到如下位置:
代码如下 |
复制代码 |
#LoadModule rewrite_module modules/mod_rewrite.so
|
将该项前面的“#”去掉后启动该项。
然后,查找httpd.conf文件,找到其中的AllowOverride项,将它的值都修改为All。保存并重新启动Apache服务器,使修改生效。
最后,在实例根目录下创建.htaccess文件,实现对PHP文件后缀的隐藏操作。.htaccess文件的代码如下:
代码如下 |
复制代码 |
RewriteEngine On#启动项
RewriteRule^index.html$ index.php
RewriteRule^ndex_ok.html$ index_ok.php
RewriteRule^index-([0-9]+)-([0-9]+)-([0-9]+)\.html$ index.php?vv=$1&ljjl=$2&page=$3[L]
|
通过正则表达式对文件的后缀和传递的参数进行匹配,完成对PHP文件后缀的隐藏操作。
以前人记得我有介绍过在php中CLI模式传参数的几个方法,下面我再来给大家详细的介绍一下关于CLI模式传参数的例子,希望例子能帮助到各位。
在CLI(命令行界面 Command Line Interface)传入参数呢的3种方法。
一. getopt函数(PHP 4 >= 4.3.0, PHP 5)
建立文件:test1.php 代码如下
<?php
$opt= getopt('m:n:');
print_r($opt);
?>
然后运行命令
php test1.php -maaaaaa -nbbbbbbb
结果如下:
array(
[m] => aaaaaa
[n] => bbbbbbb
)
详情请看手册 :http://www.php.net/manual/zh/function.getopt.php
二. $argv
建立文件:test2.php 代码如下
<?php
var_dump($argv);
?>
然后运行命令
php test2.php 1 2 3 a b c
结果如下:
array(7){
[0]=>string(9) “test2.php”
[1]=>string(1) “1″.
[2]=>string(1) “2″
[3]=>string(1) “3″
[4]=>string(1) “a”
[5]=>string(1) “b”
[6]=>string(1) “c”
}
详情参见手册:http://www.php.net/manual/zh/reserved.variables.argv.php
三. STDIN
建立文件:test3.php 代码如下
<?php
fwrite(STDOUT, "Enter your name: ");
$name = trim(fgets(STDIN));
fwrite(STDOUT, "Hello, $name!");
?>
然后运行命令
php test3.php
结果如下:
此时屏幕输出:Enter your name:
我们在后面输入:111cn.net然后回车
此时屏幕会出现Hhellow,111cn.net