【PHP 连接MySQL】

PHP 连接MySQL 工具类(第一天)

PHP 学习笔记 。使用mysqli 操作数据库

Sql工具类

<?php
/**
 * 这是一个数据库操作工具类
 * 
 * 
 * 提供的方法:
 *      初始化链接参数:__construct();
 *      链接数据库:get_connect();
 *      执行sql语句: excuteSql();
 */
class Sql{
    public $host;
    public $port;
    public $user;
    public $password;
    public $dbName;
    public $con;
    public $sqlStr;
    //构造函数
    public function __construct($host,$port,$user,$passwor,$dbName){
        $this->host=$host;
        $this->port=$port;
        $this->user=$user;
        $this->password=$passwor;
        $this->dbName=$dbName;
        
        //echo $this->host."-".$this->port."-".$this->user."-".$this->password."-".$this->dbName;
    }
    //连接mysql
    public function get_connect(){
        $this->con=mysqli_connect($this->host,$this->user,$this->password,$this->dbName,$this->port);
        mysqli_query($this->con,"set names=utf8");
        return $this->con;
    }
    //执行sql语句
    public function excuteSql($sql_str){
        if(strlen($sql_str)<=0 or $sql_str==null){
            echo "请输入sql语句";
            return null;
        }else{
           return mysqli_query($this->con,$sql_str);
        }
    }
    
    /**
     * 获取一条数据
     * 参数1:表名
     * 参数2:id
     */
    public function getSingle($tableName,$id){
        if($id!==null){
            $this->sqlStr="select * from ".$tableName." where id=".$id;
            //echo $this->sqlStr;
            return mysqli_query($this->con,$this->sqlStr);
        }else{
            echo "请提供参数 id";
        }
    }

}

// //1.链接mysql
// $con= mysqli_connect("localhost","root","root");
// //2.链接数据库
// mysqli_select_db($con,"test");
// //3.设置字符编码
// mysqli_query($con,"set names=utf8");
// //3.拼接sql 
// $sql ="select * from userindo";
// //4.执行sql
// $data=mysqli_query($con,$sql);
// //5.遍历数据
// while($res=$data->fetch_assoc()){
// echo "<p>",$res["name"],"</p>";
// }

?>

测试类

以下 test.php 文件为 Sql 工具类测试程序

<?php

include_once 'Sql.php'; //加载SQL工具类

$db=new Sql("127.0.0.1","3306","root","root","test");

$con= $db->get_connect();
if(!$con){
    die("数据库连接失败!".mysqli_connect_error());
}
//新增
$insertSql="insert into userinfo (name,password,age,sex)values('小白',123123,10,3)";
$db->excuteSql($insertSql);

//删除
$delSql="delete from userinfo where name LIKE '小白'";
$db->excuteSql($delSql);

//更新
$updateSql="update userinfo set name='张飞' where id=3";
$db->excuteSql($updateSql);

//查询
$sqlStr="select * from userinfo";
$data= $db->excuteSql($sqlStr);

$userData=$db->getSingle("userinfo",1);

while($res=$userData->fetch_assoc()){
    echo  $res["name"];
}

数据库

表名 userinfo

userinfo表字段

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值