首页 > 编程技术 > php

php 无限分类程序

发布时间:2016-11-25 17:31

以前也经常介绍关于无限分类这个问题,大多数情况我们都是利用php递归来实现,今天介绍的这篇无限分类不需要递归哦,方法很简单有需要的朋友可以参考一下。

 

 代码如下 复制代码

//////////////
//////无限分类的数据库设计及样例
//////////////
mysql> create database db_kind;
Query OK, 1 row affected

mysql> use db_kind;
Database changed
mysql> create table tb_kind(
-> id int not null auto_increment primary key,
-> pid int,
-> path varchar(200)
-> );
Query OK, 0 rows affected

mysql> insert into tb_kind values(null,"新闻",0,0);
Query OK, 1 row affected

mysql> insert into tb_kind values(null,"视频",0,0);
Query OK, 1 row affected

mysql> insert into tb_kind values(null,"图片",0,0);
Query OK, 1 row affected

mysql> insert into tb_kind values(null,"博客",0,0);
Query OK, 1 row affected

mysql> insert into tb_kind values(null,"体育新闻",1,"0-1");
Query OK, 1 row affected

mysql> insert into tb_kind values(null,"娱乐新闻",1,"0-1");
Query OK, 1 row affected

mysql> insert into tb_kind values(null,"财经新闻",1,"0-1");
Query OK, 1 row affected

mysql> select * from db_kind;
ERROR 1146 : Table 'db_kind.db_kind' doesnot exist
mysql> select * from tb
_kind;
+----+----------+-----+------+
| id | pname | pid | path |
+----+----------+-----+------+
| 1 | 新闻 | 0 | 0 |
| 2 | 视频 | 0 | 0 |
| 3 | 图片 | 0 | 0 |
| 4 | 博客 | 0 | 0 |
| 5 | 体育新闻 | 1 | 0-1 |
| 6 | 娱乐新闻 | 1 | 0-1 |
| 7 | 财经新闻 | 1 | 0-1 |
+----+----------+-----+------+
7 rows in set
mysql> insert into tb_kind values(null,"篮球新闻",5,"0-1-5");
Query OK, 1 row affected

mysql> insert into tb_kind values(null,"足球新闻",5,"0-1-5");
Query OK, 1 row affected

mysql> select * from tb_kind;
+----+----------+-----+-------+
| id | pname | pid | path |
+----+----------+-----+-------+
| 1 | 新闻 | 0 | 0 |
| 2 | 视频 | 0 | 0 |
| 3 | 图片 | 0 | 0 |
| 4 | 博客 | 0 | 0 |
| 5 | 体育新闻 | 1 | 0-1 |
| 6 | 娱乐新闻 | 1 | 0-1 |
| 7 | 财经新闻 | 1 | 0-1 |
| 8 | 篮球新闻 | 5 | 0-1-5 |
| 9 | 足球新闻 | 5 | 0-1-5 |
+----+----------+-----+-------+
9 rows in set

mysql> insert into tb_kind values(null,"NBA",8,"0-1-5-8");
Query OK, 1 row affected

mysql> insert into tb_kind values(null,"CBA",8,"0-1-5-8");
Query OK, 1 row affected

mysql> select * from tb_kind;
+----+----------+-----+---------+
| id | pname | pid | path |
+----+----------+-----+---------+
| 1 | 新闻 | 0 | 0 |
| 2 | 视频 | 0 | 0 |
| 3 | 图片 | 0 | 0 |
| 4 | 博客 | 0 | 0 |
| 5 | 体育新闻 | 1 | 0-1 |
| 6 | 娱乐新闻 | 1 | 0-1 |
| 7 | 财经新闻 | 1 | 0-1 |
| 8 | 篮球新闻 | 5 | 0-1-5 |
| 9 | 足球新闻 | 5 | 0-1-5 |
| 10 | NBA | 8 | 0-1-5-8 |
| 11 | CBA | 8 | 0-1-5-8 |
+----+----------+-----+---------+
11 rows in set

mysql> select concat(path,"-",id) from tb_kind;
+---------------------+
| concat(path,"-",id) |
+---------------------+
| 0-1 |
| 0-2 |
| 0-3 |
| 0-4 |
| 0-1-5 |
| 0-1-6 |
| 0-1-7 |
| 0-1-5-8 |
| 0-1-5-9 |
| 0-1-5-8-10 |
| 0-1-5-8-11 |
+---------------------+
11 rows in set

mysql> select concat(path,"-",id) from tb_kind;
+---------------------+
| concat(path,"-",id) |
+---------------------+
| 0-1 |
| 0-2 |
| 0-3 |
| 0-4 |
| 0-1-5 |
| 0-1-6 |
| 0-1-7 |
| 0-1-5-8 |
| 0-1-5-9 |
| 0-1-5-8-10 |
| 0-1-5-8-11 |
+---------------------+
11 rows in set

mysql> select concat(path,"-",id) as abs from tb_kind order by abs.path;
ERROR 1054 : Unknown column 'abs.path' in 'order clause'
mysql> select concat(path,"-",id) as abs from tb_kind order by abs

+------------+
| abs |
+------------+
| 0-1 |
| 0-1-5 |
| 0-1-5-8 |
| 0-1-5-8-10 |
| 0-1-5-8-11 |
| 0-1-5-9 |
| 0-1-6 |
| 0-1-7 |
| 0-2 |
| 0-3 |
| 0-4 |
+------------+
11 rows in set
mysql> select concat(path,"-",id) as,id,name,path abs from tb_kind order by abs;
ERROR 1064 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'id,name,path abs from tb_kind order by abs' at line 1
mysql> select concat(path,"-",id) as abs,
id,pname,path abs from tb_kind order by abs;
+------------+----+----------+---------+
| abs | id | pname | abs |
+------------+----+----------+---------+
| 0-1 | 1 | 新闻 | 0 |
| 0-1-5 | 5 | 体育新闻 | 0-1 |
| 0-1-5-8 | 8 | 篮球新闻 | 0-1-5 |
| 0-1-5-8-10 | 10 | NBA | 0-1-5-8 |
| 0-1-5-8-11 | 11 | CBA | 0-1-5-8 |
| 0-1-5-9 | 9 | 足球新闻 | 0-1-5 |
| 0-1-6 | 6 | 娱乐新闻 | 0-1 |
| 0-1-7 | 7 | 财经新闻 | 0-1 |
| 0-2 | 2 | 视频 | 0 |
| 0-3 | 3 | 图片 | 0 |
| 0-4 | 4 | 博客 | 0 |
+------------+----+----------+---------+
11 rows in set
mysql>

php处理分类源码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<!--显示结果
新闻
体育新闻
篮球新闻
NBA
CBA
足球新闻
娱乐新闻
财经新闻
视频
图片
博客
-->
<?
$conn=mysql_connect("localhost","root","root");
mysql_select_db("db_kind");
mysql_query("set names utf8");
$sql="select concat(path,'-',id) as abspath,id,pname,path from tb_kind order by abspath";
$rs=mysql_query($sql);
while($result=mysql_fetch_assoc($rs)){
$num=count(explode("-",$result[path]))-1;
$new_str=str_repeat("---",$num);
echo $new_str.$result[pname];
echo "<br>";
}
$str=str_repeat("=",10);
echo $str;
$num=count(explode("-","0-1-5-8"))-1;
echo $num;
?>
</body>
</html>

文章介绍一个实用的函数,我们如果用php substr来截取字符在中文上处理的很有问题,今天自己写了一个比较好的中文与英文字符截取的函数,有需要的朋友可以参考下。
 代码如下 复制代码

function smssubstr($string, $length) {
 if(strlen($string) <= $length) {
  return $string; 
 }
 $strcut = '';
 for($i = 0; $i < $length; $i++) {
  $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
 }
 return $strcut;
}

for($i=1; $i<=$smsnum; $i++){
 ${'smnrent'.$i} = smssubstr($message,$smsper);
 $message = str_replace(${'smnrent'.$i},"",$message);
}

好了,有需要的朋友拿去吧,原理我也不说多了,可以用就行了。

这里统计了php中大量的四舍五入函数,包括有round(),ceil(),floor()等,有需要的朋友参考一下。
 代码如下 复制代码
<?php
  $s = rand(100,200);  
  $pi=pi();
  $r=sqrt($s/$pi);
  $qz1=round($r);   //四舍五入取整
  $qz2=ceil($r);    //进一法取整
  $qz3=floor($r);   //舍去法取整
 
  echo "随机产生的圆的面积为:".$s."<br>";
  echo "通过除法和开方计算出的圆的半径为:".$r."<br>";
  echo "四舍五入取整后:".$qz1."<br>";
  echo "进一法取整后:".$qz2."<br>";
  echo "舍去法取整后:".$qz3."<br>";
 ?>
这是自己开发用到的一个简单的购物车功能的php代码,用了几个文件没用数据库就实现了购物车这样做如果用户关了浏览器,购物车里的商品就会全部丢失哦,有需要的朋友可以改进一下,利用数据库+session +cookie来实现会很好一些。
 代码如下 复制代码

<?php
class Shopcar
{
//商品列表
public  $productList=array();

/**
 *
 * @param unknown_type $product 传进来的商品
 * @return true 购物车里面没有该商品
 */
public function checkProduct($product)
{
 
 for($i=0;$i<count($this->productList);$i++ )
 {
 
  if($this->productList[$i]['name']==$product['name'])  
  return $i;
 }
 
 return -1;

}
 //添加到购物车
 public function add($product)
{
 $i=$this->checkProduct($product);
 if($i==-1)
 array_push($this->productList,$product);
 else
 $this->productList[$i]['num']+=$product['num']; 
}
//删除
public function delete($product)
{
 $i=$this->checkProduct($product);
 if($i!=-1)
 array_splice($this->productList,$i,1);
 
}

//返回所有的商品的信息
public function show()
{
  return $this->productList;

}


}

html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript"" width=100% src='jquery.min.js'></script>
<script type="text/javascript">
function buy(i)
{
var num=$(':input[name=num]')[i].value;
var name=$('[name=name]')[i].innerHTML;
var price=$('[name=price]')[i].innerHTML;

alert(num+name+price);
$.ajax({
  type:'post',                    //传送的方式,get/post
  url:'index.php',   //发送数据的地址
  cache:'false',
  data:'num='+num+"&name="+name+"&price="+price,            
  success:function(data)
  {
  alert(data);
  }
})

 

}


</script>
</head>
<body>

<table>
<tr><td>商品编号</td><td>商品名称</td><td>价格</td><td>数量</td><td>购买</td></tr>

<tr><td>0</td><td><label name='name' >商品1</label></td><td><label name='price'>1</label>
</td><td><input  name='num' type='text' value='1' /></td><td><a  onclick='buy(0)'><u><font color='blue'>购买</font></u></a></td></tr>

<tr><td>1</td><td><label name='name' >商品2</label></td><td><label name='price'>2</label>
</td><td><input  name='num' type='text' value='1' /></td><td><a  onclick='buy(1)'>购买</a></td></tr>

<tr><td>2</td><td><label name='name' >商品3</label></td><td><label name='price'>1</label>
</td><td><input  name='num' type='text' value='1' /></td><td><a  onclick='buy(2)'>购买</a></td></tr>
<tr><td>3</td><td><label name='name' >商品4</label></td><td><label name='price'>1</label>
</td><td><input  name='num' type='text' value='1' /></td><td><a  onclick='buy(3)'>购买</a></td></tr>

<tr><a href='show.php'>查看购物车</a></tr>

 


</table>

</body>
</html>
index.ph

<?php
require 'Shopcar.class.php';
session_start();

$name=$_POST['name'];
$num=$_POST['num'];
$price=$_POST['price'];
$product=array('name'=>$name,'num'=>$num,'price'=>$price);
print_r($product);
if(isset($_SESSION['shopcar']))
$shopcar=unserialize($_SESSION['shopcar']);
else
$shopcar=new Shopcar();
$shopcar->add($product);
$_SESSION['shopcar']=serialize($shopcar);

show.php

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<table>
<tr><td>商品编号</td><td>商品名称</td><td>价格</td><td>数量</td></tr>
<?php
require 'Shopcar.class.php';
session_start();
$shopcar=unserialize($_SESSION['shopcar']);

print_r($shopcar);
$productList=$shopcar->productList;

foreach ($productList as $product){
?>
<tr><td>1</td><td><label ><?php echo $product['name']?></label></td><td><label name='price'><?php echo $product['price']?></label>
</td><td><input  name='num' type='text' value='<?php echo $product['num']?>' /></td></tr>
<?php }?>
</table>
</body>
</html>

本文章主要讲到了jquery中的ajax和php结合,实现用户无刷新登录效果,有需要的朋友可以参考一下。

本例我们使用Mysql数据库,创建一张user表,表结构如下:

 代码如下 复制代码

CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(30) NOT NULL COMMENT '用户名',
  `password` varchar(32) NOT NULL COMMENT '密码',
  `login_time` int(10) default NULL COMMENT '登录时间',
  `login_ip` varchar(32) default NULL COMMENT '登录IP',
  `login_counts` int(10) NOT NULL default '0' COMMENT '登录次数',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
然后往user表中插入一条用户信息数据:

INSERT INTO `user` (`id`, `username`, `password`, `login_time`, `login_ip`, `login_counts`)
 VALUES(1, 'demo', 'fe01ce2a7fbac8fafaed7c982a04e229', '', '', 0);

用户在输入用户名和密码后,提示用户登录成功,并显示相关登录信息,如果点击“退出”,则退出到用户登录界面。

进入index.php,如果用户已登录则显示登录信息,如果未登录则显示登录框要求用户登录。

 代码如下 复制代码

<div id="login">
      <h3>用户登录</h3>
      <?php
      if(isset($_SESSION['user'])){
      ?>
      <div id="result">
        <p><strong><?php echo $_SESSION['user'];?></strong>,恭喜您登录成功!</p>
        <p>您这是第<span><?php echo $_SESSION['login_counts'];?></span>次登录本站。</p>
        <p>上次登陆本站的时间是:<span><?php echo date('Y-m-d H:i:s',$_SESSION['login_time']);?>
</span></p><p><a href='#' id='logout'>【退出】</a></p>
      </div>
      <?php }else{?>
      <div id="login_form">
          <p><label>用户名:</label> <input type="text" class="input" name="user" id="user" /></p>
          <p><label>密 码:</label> <input type="password" class="input" name="pass" id="pass" />
</p>
          <div class="sub">
              <input type="submit" class="btn" value="登 录" />
          </div>
      </div>
      <?php }?>
</div>

注意在index.php文件头应该加上语句:session_start; 同时在head部分引入jquery库,以及包含global.js,您还可以为登录框写个漂亮的CSS样式,当然本例已经略微写了个简单的样式,请查看源码。

 代码如下 复制代码

<script type="text/javascript"" width=100% src="../Script/jquery.js"></script>
<script type="text/javascript"" width=100% src="./Script/global.js"></script> 

global.js文件包括了将要实现的jquery代码。首先要做的就是让输入框获得焦点,像百度和google那样一打开,鼠标光标就在输入框内。使用代码如下:

 代码如下 复制代码

$("input:text,textarea,input:password").focus(function() {
    $(this).addClass("cur_select");
});
$("input:text,textarea,input:password").blur(function() {
    $(this).removeClass("cur_select");
});

用户登录
用户点击登录按钮后,首先要验证用户的输入不能为空,然后向后台login.php发送一个Ajax请求。当后台验证登录成功后,返回登录用户信息:如用户登录次数和上次登录时间等;如果登录失败,则返回登录失败信息。

 代码如下 复制代码
$(".btn").live('click',function(){
    var user = $("#user").val();
    var pass = $("#pass").val();
    if(user==""){
        $('<div id="msg" />').html("用户名不能为空!").appendTo('.sub').fadeOut(2000);
        $("#user").focus();
        return false;
    }
    if(pass==""){
        $('<div id="msg" />').html("密码不能为空!").appendTo('.sub').fadeOut(2000);
        $("#pass").focus();
        return false;
    }
    $.ajax({
        type: "POST",
        url: "login.php?action=login",
        dataType: "json",
        data: {"user":user,"pass":pass},
        beforeSend: function(){
            $('<div id="msg" />').addClass("loading").html("正在登录...").css("color","#999")
.appendTo('.sub');
        },
        success: function(json){
            if(json.success==1){
                $("#login_form").remove();
                var div = "<div id='result'><p><strong>"+json.user+"</strong>,恭喜您登录成功!</p>
                <p>您这是第<span>"+json.login_counts+"</span>次登录本站。</p>
                <p>上次登录本站的时间是:<span>"+json.login_time+"</span></p><p>
                <a href='#' id='logout'>【退出】</a></p></div>";
                $("#login").append(div);
            }else{
                $("#msg").remove();
                $('<div id="errmsg" />').html(json.msg).css("color","#999").appendTo('.sub')
.fadeOut(2000);
                return false;
            }
        }
    });
});

我在进行Ajax请求时,数据传输格式使用的是json,返回的数据也是json数据,使用JS将json数据解析,得到登录后的用户信息,然后通过append追加到#login元素下,完成登录操作。

用户退出
当点击“退出”时,向login.php发送一个Ajax请求,后台注销所有Session,页面重新回到登录界面。

 代码如下 复制代码

$("#logout").live('click',function(){
    $.post("login.php?action=logout",function(msg){
        if(msg==1){
             $("#result").remove();
             var div = "<div id='login_form'><p><label>用户名:</label> 
             <input type='text' class='input' name='user' id='user' /></p>
             <p><label>密 码:</label> <input type='password' class='input' name='pass' 
id='pass' /></p>
             <div class='sub'><input type='submit' class='btn' value='登 录' /></div>
             </div>";
             $("#login").append(div);
        }
    });
});

login.php
根据前台提交的请求,登录时,获取用户输入的用户名和密码,并与数据库中对应的用户名和密码进行比对,如果比对成功,则将新的更新该用户登录信息,并组装json数据传给前台。

 代码如下 复制代码
session_start();
require_once ('connect.php');
 
$action = $_GET['action'];
if ($action == 'login') {  //登录
    $user = stripslashes(trim($_POST['user']));
    $pass = stripslashes(trim($_POST['pass']));
    if (empty ($user)) {
        echo '用户名不能为空';
        exit;
    }
    if (empty ($pass)) {
        echo '密码不能为空';
        exit;
    }
    $md5pass = md5($pass); //密码使用md5加密
    $query = mysql_query("select * from user where username='$user'");
 
    $us = is_array($row = mysql_fetch_array($query));
 
    $ps = $us ? $md5pass == $row['password'] : FALSE;
    if ($ps) {
        $counts = $row['login_counts'] + 1;
        $_SESSION['user'] = $row['username'];
        $_SESSION['login_time'] = $row['login_time'];
        $_SESSION['login_counts'] = $counts;
        $ip = get_client_ip(); //获取登录IP
        $logintime = mktime();
        $rs = mysql_query("update user set login_time='$logintime',login_ip='$ip',
login_counts='$counts'");
        if ($rs) {
            $arr['success'] = 1;
            $arr['msg'] = '登录成功!';
            $arr['user'] = $_SESSION['user'];
            $arr['login_time'] = date('Y-m-d H:i:s',$_SESSION['login_time']);
            $arr['login_counts'] = $_SESSION['login_counts'];
        } else {
            $arr['success'] = 0;
            $arr['msg'] = '登录失败';
        }
    } else {
        $arr['success'] = 0;
        $arr['msg'] = '用户名或密码错误!';
    }
    echo json_encode($arr); //输出json数据
}
elseif ($action == 'logout') {  //退出
    unset($_SESSION);
    session_destroy();
    echo '1';
}

当前台请求退出时,只需注销session就可以,并返回1给前台JS处理。注意上述代码中get_client_ip()是获取客户端IP的函数,限于篇幅未能列出。

 

标签:[!--infotagslink--]

您可能感兴趣的文章: