PHP:MySQL数据库操作
连接数据库的步骤:(有一定的想法和思维,做事事半功倍)
1.连接数据库
2.设置编码
3.选择数据库
4.组合sql语句
5.执行sql语句
6.关闭连接
1.连接数据库、关闭数据库
<?php
class db{
private $conn;
// 实例化数据库
public function __construct()
{
$this->conn=mysqli_connect(host:'127.0.0.1',user:'root',password:'root',database:'dome');
mysqli_set_charset($this->conn,charset:'utf8');
}
// 销毁时关闭数据库
public function __destruct()
{
mysqli_close($this->conn);
}
}
2.查询一条SQL语句
// 查询一条sql语句
function get_one($table,$where=''){
$sql='selsct * from `'.$table.'`';
if(!empty($where)){
$sql .=' where '.$where;
}
$result=mysqli_query($this->conn,$sql);
if($result){
if(mysqli_num_rows($result)>0){
$arr=mysqli_fetch_all($result,resulttype:MYSQLI_ASSOC);
return $arr[0];
}
}
}
3.查询所有SQL语句
// 查询所有SQL语句
function get_all($table,$where=''){
$sql='selsct * from `'.$table.'`';
if(!empty($where)){
$sql .=' where '.$where;
}
$result=mysqli_query($this->conn,$sql);
if($result){
if(mysqli_num_rows($result)>0){
$arr=mysqli_fetch_all($result,resulttype:MYSQLI_ASSOC);
return $arr;
}
}
}
4.添加SQL语句
// 添加SQL语句
function add($table,$data){
$sql='insert into `'.$table.'`(';
$sql_field=',';
$sql_value=',';
$n=1;
$count= count($data);
foreach($data as $k=>$d){
$sql_field .='`'.$k.'`';
$sql_value .='`'.$d.'`';
if($n<$count){
$sql_field .=',';
$sql_value .=',';
}
$n++;
}
$sql .= $sql_field.')';
$sql .= 'value('.$sql_value.');';
$result=mysqli_query($this->conn,$sql);
if($result){
return true;
}
return false;
}
5.修改SQL语句
// 修改SQL语句
function update($table,$data,$where=''){
$sql = 'update`'.$table.'`ste';
$sql_set = '';
$n = 1;
$count= count($data);
foreach($data as $k=>$d){
$sql_set = '`'.$k.'`="'.$d.'"';
if($n<$count){
$sql_set .=',';
}
$n++;
}
$sql .= $sql_set;
if(!empty($where)){
$sql .= ' where '.$where;
}
$result=mysqli_query($this->conn,$sql);
if($result){
return true;
}
return false;
}
6. 删除
// 删除
function delete($table,$where = ''){
$sql = 'delete from `'.$table.'`';
if(!empty($where)){
$sql.=' where '.$where;
}
$result=mysqli_query($this->conn,$sql);
if($result){
return true;
}
return false;
}
注
:命名变量看个人习惯,但一定要规范
当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »