php+mysql案例1

来源:互联网 发布:语音直播间源码 编辑:程序博客网 时间:2024/06/05 23:54

面向过程方式:

<?php
/*
 * Created on 2011-3-31
 * php和MYSQL建立连接
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
//1.建立连接
$conn = mysql_connect("localhost","root","123456") or die("连接失败");
//2.指定数据库
mysql_select_db("yd_test",$conn) or die("失败");
//3.指定编码
mysql_query("set names 'gbk'");

?>

面向对象方式:

<?php
/*
 * PHP+MySQL
 * 吕老师教学视频
 * 面向对象
 */

 //定义封装的类:公共的数据库类
 class MySQL{
    private $host;//主机
    private $name;//用户名
    private $pass;//密码
    private $database;//数据库
    private $charset;//编码
    private $conn;//连接
    //用set get函数
    function __set($n,$v){
        $this->$n=$v;
    }
    function __get($n){
        return $this->$n;
    }
    //构造函数赋值
    function __construct($host,$name,$pass,$db,$cs){
        $this->host=$host;
        $this->name=$name;
        $this->pass=$pass;
        $this->database=$db;
        $this->charset=$cs;
        $this->conn=$this->getConn();
    }
    //得到链接
     function getConn(){
         $conn =  mysql_connect($this->host,$this->name,$this->pass) or die("连接失败");
        mysql_select_db($this->database,$conn) or die("失败");
        mysql_query("set names '$this->charset'");
        return $conn;
     }

    function myUpdate($sql){
        $res = mysql_query($sql,$this->conn) or die(mysql_error());
        if($res>0){
            echo "成功";
        }else{
            echo "失败";
        }
        return $res;
    }

    function myFetch($result){
        $row = mysql_fetch_array($result);
        return $row;
    }
//吕老师教学视频-http://www.tudou.com/home/xuexi158


 }



?>
 

原创粉丝点击