PHP数据库编程②自写PHP连接数据库并且操作数据库函数SQLtool_class.php

SQLtool_class.php



    class SQLtool{
        private $conn;
        private $host="localhost";
        private $user="root";
        private $password="root1142495240";
        private $db="123"; //指定所链接数据库
        function SQLtool(){
            $this->conn=mysql_connect($this->host,$this->user,$this->password);
            if (!$this->conn){
                die("数据库链接出问题啦".mysql_error());
            }
            mysql_select_db($this->db,$this->conn);
        }
        //完成select
        public function execute_dql($sql){
            $res=mysql_query($sql) or die (mysql_error());
            return $res;

        }
        public function execute_dml($sql){
            $b=mysql_query($sql,$this->conn);
            if (!$b){
                return 0;//失败
            }else {
                if (mysql_affected_rows($this->conn)>0){
                    return 1;//表示真的成功
                }else {
                    return 2;//表示没有行数影响
                }
            }
        }
    }

操作SQLtool_class.php的PHP页面

$sql="delete from user1 where id=数";
    //更新:$sql="updata user1 set age=100 where id = 数值";
/*  $conn=mysql_connect("localhost","root","root1142495240");
    if (!$conn){
        die("链接数据库出错la".mysql_error());
    }
    mysql_select_db("123",$conn);
    mysql_query("set names utf8");
    $sql="insert into user1 (name,password,age) values('小明','1111','55')";

    $res=mysql_query( $sql,$conn);
    if (!$res){
        echo "操作失败".mysql_error();
    }else {
        echo "操作成功";
    }
    mysql_close($conn);

*/
/*****************dml操作**************/
    require_once 'SQLtool_class.php';
    $sql="insert into user1 (name,password,age) values('小明','1111','55')";
    $sqltool=new SQLtool();
    $res=$sqltool->execute_dml($sql);
    if ($res==0){
        echo "失败";
    }else if ($res==1){
        echo "成功";
    }else if ($res==2){
        echo "没有行数影响";
    }

/*****************dql操作**************/
    $sql="select * from user1";
    $res=$sqltool->execute_dql($sql);
    while ($row=mysql_fetch_row($res)){
        foreach ($row as $key=>$val){
            echo "--$val";
        }
        echo "
"
; } mysql_free_result($res);

你可能感兴趣的:(php)