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"];
}