学了面向对象,写了一个数据库类,以后就可以傻瓜化调用这个数据库了。

3 篇文章 0 订阅
1 篇文章 0 订阅
之前熟悉开发新闻管理系统,一直不知道分类管理怎么写。每次问百度,搜索结果都不一样,终于有一次,查到这套视频,中间有教开发CMS的题目。
我直接从开发CMS学起,开发分类管理功能我比较陌生,增删改查不是问题。视频上老师调用以前写好的面向对象数据库类做文章增删改查,我都不知老师的类怎么写的,我就用面向过程做增删改查。
完整CMS写出来了,这套视频是我见过最好的视频。写了CMS,又从头开始打基础,决定把整套视频完整看一遍。
学习没压力,半个月后看到面向对象。面向对象,之前看着都有点烦,看过很多书,写到面向对象也是一笔带过,现在看面向对象也是觉得有点绕来绕去的。没办法,必须学的。
学的过程中,很容易不小心就出错,但还是用5个小时学完面向对象那一章。
不要觉得按视频写完了代码,以后就知道只管傻瓜化调用。还要多看、深入理解和记住代码。


下面贴出代码,数据库类文件db.class.php,是让别的文件调用的。

<?php
header("content-type:text/html;charset=utf-8");
class DB{
	public $dbHost;
	public $userName;
	public $userPwd;
	public $char;
	public $dbName;

	function __construct($host,$un,$up,$dbn){
		//如果没有参数传递,使用的是默认值。如果有新值传递,使用新值。
		$this->dbHost=$host;
		$this->userName=$un;
		$this->userPwd=$up;
		$this->dbName=$dbn;
		echo $this->dbHost;
		//echo $this->userName;
		//echo $this->userPwd;
		//echo $this->char;
		echo $this->dbName;

		//实例化的时候执行连接数据库动作。
		$link=mysql_connect($this->dbHost,$this->userName,$this->userPwd);
		//echo $link;
		mysql_select_db($dbn,$link);
	}

	//执行sql语句的方法。
	function query($sql){
		return mysql_query($sql);
	}

	//统计记录数 mysql_num_rows
	function num($sql){
		$result=$this->query($sql);
		return mysql_num_rows($result);
	}

	function affected(){
		return mysql_affected_rows();
	}

	function fetchOne($sql){
		$result=$this->query($sql);
		$rs=mysql_fetch_assoc($result);
		return $rs;
	}

	function fetchAll($sql){
		$result=$this->query($sql);
		$rows=array();
		while($rs=mysql_fetch_assoc($result)){
			$rows[]=$rs;
		}
		return $rows;//返回二维数组。
	}

	function __destruct(){
		$this->dbHost	 =NULL;
		$this->userName  =NULL;
		$this->userPwd	 =NULL;
		$this->dbName 	 =NULL;
	}
}

$db=new DB("localhost","root","123456","数据库");

?>


调用数据库类文件。

<?php
include 'DB.class.php';
$sql="select * from category";
$rs=$db->fetchAll($sql);
print_r($rs);
?>
<table>
	<tr>
		<td>分类ID</td>
		<td>分类父ID</td>
		<td>分类名</td>
	</tr>
<?php
	foreach ($rs as $key => $val) {
?>
	<tr>
		<td><?php echo $val["category_id"];?></td>
		<td><?php echo $val["category_parent_id"];?></td>
		<td><?php echo $val["category_name"];?></td>
	</tr>
<?php
	}
?>
<table>



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值