谢谢了,就是一个连数据库的类
<?php
class db{
public $conn;
function __construct(){
$this->conn=mysqli_connect('localhost','root','123123','air');
//$this->conn->query('SET NAMES UTF8');
mysqli_query($this->conn,'SET NAMES UTF8');
}
public function delete($table,$condition=""){
if(empty($condition)) {
$this->halt('没有设置删除的条件');
return false;
}
$sql = "delete from ".$table." where 1=1 and ".$condition;
if(!$this->conn->query($sql)){
return false;
}else{
return true;
}//if
}
public function getAll($sql){//输出数组所有
$rt=array();
$q=$this->conn->query($sql);
$this->conn->query('SET NAMES UTF8');
while($r=$q->fetch_array(MYSQLI_USE_RESULT)){
$rt[]=$r;
}
return $rt;
}
public function __destruct(){
mysqli_close($this->conn);
}
}//db
?>
<?php
class db{
public $conn;
function __construct(){
$this->conn=mysqli_connect('localhost','root','123123','air');
//$this->conn->query('SET NAMES UTF8');
mysqli_query($this->conn,'SET NAMES UTF8');
}
public function delete($table,$condition=""){
if(empty($condition)) {
$this->halt('没有设置删除的条件');
return false;
}
$sql = "delete from ".$table." where 1=1 and ".$condition;
if(!$this->conn->query($sql)){
return false;
}else{
return true;
}//if
}
public function getAll($sql){//输出数组所有
$rt=array();
$q=$this->conn->query($sql);
$this->conn->query('SET NAMES UTF8');
while($r=$q->fetch_array(MYSQLI_USE_RESULT)){
$rt[]=$r;
}
return $rt;
}
public function __destruct(){
mysqli_close($this->conn);
}
}//db
?>
if(!$this->conn->query($sql)){
return false;
}else{
return true;
}
这个好像也可以单独拿出来写成一个function吧。
第二:组织sql语句应该放在逻辑层(按照MVC设计模式)
第三:对数据库的操作的类,一般写一个dml(修改),dql(查询)两个函数。所以你的那个getAll不应该写在这个类中(我一般写代码这个类喜欢叫SqlHelper.class.php,里面写一个execute_dml函数,和一个execute_dql函数,构造函数用于连接数据库)
呵呵!!!我也是刚刚学PHP,菜鸟一个。以上只是我个人见解,不知道对还是不对
这样代码生成器就是必须的,
做下广告
http://download.csdn.net/detail/jia5255/4722666,免费的。
比如说你这个类, 有insert, 有query(getAll), 没看见update, 要么是你没贴全, 但是如果你的应用目前和将来都不需要update, 那没有也没什么错. 随便说点细节上的东西:
1. 'SET NAMES UTF8' 没必要在getAll里, 连接后运行一次即可.
2. $this->conn->query和mysqli_query混用, 统一比较好看
3. delete($table,$condition="")和getAll($sql), 接口不一致, 使用你这个类的会比较头疼
4. mysqli_connect和$this->conn->query之后都最好检查错误
.....
x. 代码没贴全: $this->halt是什么?
update之实现原理与select一样,为了节省阅读时间,故而并无示展。
1.我修改的对吗?
public function __destruct(){
$this->conn->close();//有()吗?还是直接close
}
2.为什么?$mysqli->errno;无()号,而$mysqli->close();要而()号?手册上都是方法啊?
3.delete给他一个条件,就能删除,故只要一个条件即可。而getall可能是很复杂的左右连接,故直接把sql转过去,接口?我不会,是何意?谢谢