• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP封装数据库连接

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

用类封装数据库连接(unionsql-class.php)

<?php
class DBDA
{
    public $host="localhost";//服务器地址
    public $uid="root";//用户名
    public $pwd="";//密码
    
    public $dbconnect;//连接对象
    //操作数据库的方法
    //$sql代表需要执行的SQL语句
    //$type代表SQL语句的类型,1代表查询,2代表增删改
    //$dbname代表要操作的数据库名称
    //如果是查询,返回二维数组
    //如果是增删改,返回true或false
    function Query($sql,$type=1,$dbname="newssystem")
    {
        //造链接对象
        $this->dbconnect=new MySQLi($this->host,$this->uid,$this->pwd,$dbname);
        //判断是否出错
        if(!mysqli_connect_error())
        {
            //如果成功,执行SQL语句
            $result=$this->dbconnect->query($sql);
            //根据语句了类型判断
            if($type==1)
            {
                //如果是查询语句,就返回二维数组
                return $result->fetch_all();            }
            else
            {
                //如果是其他语句,就返回true和false
                return $result;
            }
        }
        else
        {
            return "链接失败!";
        }
    }
}

其他页面调用:

$title=$_POST["title"];
$author=$_POST["author"];
$source=$_POST["source"];
$content=$_POST["content"];
$time=date("Y-m-d H:i:s");




include("DBDA.class.php");
$db=new DBDA();
$sql="insert into news values('','{$title}','{$author}','{$source}','{$content}','{$time}')";//没有定义的不写,比如前面第一个自增长的
if($db->Query($sql,2)==true)//
{
    header("location:fabuxinwenshouye.php");
}
else
{
    echo "注册失败";
}

用函数封装数据库连接(unionsql-function.php)

function unionsql($sql,$host='localhost',$usename='root',$password='',$mysql='index')
{
    $db=new MySQLi($host,$usename,$password,$mysql);
    !mysqli_connect_error() or die('连接失败');
    $result=$db->query($sql);
    $sql=ltrim($sql," ");
    $str=substr($sql,0,6);
    $type=1;
    if($str=='select')
    {
        $type=0;
    }
    if($type==0)
    {
        return $result->fetch_all();
    }
    else
    {
        return $result;
    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
php改变header头返回值发布时间:2022-07-10
下一篇:
PHP实现多继承发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap