php数据库使用

  • 1、php数据库编程

三种方式操作mysql数据库:

1、mysql扩展库
2、mysqli 扩展库
3、pdo

  • 2、mysql扩展库和mysql数据库的区别。
    2.1 扩展库是php里面的一些函数,方便程序员操作mysql数据库。mysql是用于存放数据的,主要的是数据表。(还有其他的数据对象)
    2.2 数据库的三层结构:php程序==》dnms==>数据库
    
    php数据库使用_第1张图片
    Paste_Image.png
  • 3、 使用php的mysql扩展库对mysql操作的案例。

3.1 启用mysql扩展库
在php.ini文件中配置,extension=hph_mysql.dll

 $value) {
        echo "---$value";
    }
}
// 6、释放资源,关闭链接
mysql_free_result($res);
mysql_close($conn);// 可以有
?>


  • 4.mysqli的使用(面向对象)
connect_error){
    die("链接失败".$mysqli->connect_error);
}
// 2.操作数据库
$sql = "select *from user1";
//返回结果
$res = $mysqli->query($sql);
//3.处理结果
while($row=$res->fetch_row()){
      foreach($row as $key=>$val){
          ech "$val--";
}
// 4.关闭资源
$res->free(); // 释放内存
$mysqli->close();//关闭链接
?>
  • 5.mysqli的使用(面向过程)省略

注意事项:如果操作的字段类型是String类型,则要求我们要用单引号括起来,如果操作字段是值类型,则不要求用单引号。

  • 6.再封装一层
mysqli=new MySQLi(self::$host,self::$user,self::$pwd,self::$db);
        if($this->mysqli->connect_error){
            die("错误".$this->mysqli->connect_error);
            $this->mysqli->query("set names utf8");
        }
    }

    public function execute_dql($sql) {
        $res=$this->mysqli->query($sql) or die("操作dql").$this->mysql->error);
        return $res;
    }
    public function execute_dml($sql) {
        $res=$this->mysqli->query($sql) or die("操作dql").$this->mysql->error);

        if (!$res) {
            return 0;//表示失败
        } else {
            if($this->mysqli->affected_rows>0){
                        return 1;//表示成功
                    }else {
                    return 2;// 表示没有行受到影响   
                    }
        }
    }

}
?>

你可能感兴趣的:(php数据库使用)