当我们写一个项目的时候,可能会在多个php文件中对数据库进行操作,我们可以把这些操作封装成方法,然后在需要用到的php文件中引入该php文件就可以了
我们建一个 mySql.php文件
<?php
$link = mysqli_connect("localhost","root","","mydb");
mysqli_set_charset($link,"utf8");
if(mysqli_connect_errno($link)){
echo "错误号:".mysqli_connect_errno($link);
echo "<br>错误描述:网站错误,请联系管理员";
return false;
}
//插入的方法
function insert($link,$fields,$table){
$sql = " insert into ";
$sql = $sql.$table." set ";
$string = "";
foreach($fields as $key => $val){
$string .= $key."='".$val."',";
//echo $string."<br>";
}
$string = trim($string,",");
$sql .= $string;
//echo $sql."<br>";
mysqli_query($link,$sql);
}
//查询多条方法
function getAll($link,$fields,$table,$where){
$sql = "select ";
$sql .= $fields;
$sql .= " from ".$table;
$sql .= " where ". $where;
//echo $sql."<br>";
$result = mysqli_query($link,$sql);
//以关联数组形式返回
return mysqli_fetch_all($result, MYSQLI_ASSOC);
}
//查询单条的方法
function getOne($link,$fields,$table,$where){
$sql = "select ";
$sql .= $fields;
$sql .= " from ".$table;
$sql .= " where ".$where;
//echo $sql."<br>";
//执行查询,如果有记录返回结果集
$result = mysqli_query($link,$sql);
//通过结果集方法返回一条数据
if($result) {
return mysqli_fetch_assoc($result);
}else {
return false;
}
}
?>
在需要用到的 PHP 文件中引入 mySql 文件
eg:
include "mysql.php";
// 调用 getAll 方法传入参数
$data = getAll($link,"*","menu"," 1=1 ");
echo json_encode($data);
我的博客链接
更多资源就在我的gitHub:https://github.com/huzixian2017/huzixian2017.github.io