1.上工具代码:DBUtils.php
header("Content-Type:text/html;charset=utf-8");
/*
* php->mysql*/
class DBUtil
{
private static $servername="localhost";
private static $db_username ="root"; //用户名"mysql8256553";
private static $db_password ="1999y4m30D"; //密码*/ "1999y4m30D";
private static $db_name="mysql8256553_db";
/*连接方法*/
public static function DBConnect(): mysqli
{
$conn=null;
$conn = mysqli_connect(self::$servername,self::$db_username,self::$db_password,self::$db_name);
if ($conn!=null){
// echo "Connection success";
//return "success";
}else{
die("Connection failed: " . mysqli_connect_error());
}
return $conn;
}
/*关闭方法*/
public static function DBClose($conn){
$conn->close();
//echo "连接已关闭";
}
/*查询方法*/
public static function DBSelect($conn,$sql){
// 设置编码,防止中文乱码
mysqli_set_charset($conn, "utf8");
// 选择数据库
mysqli_select_db($conn,"mysql8256553_db");
$result=null;
$result=mysqli_query($conn,$sql);
return $result;
}
/*删除方法*/
public static function DBDelete($conn,$sql){
// 设置编码,防止中文乱码
mysqli_set_charset($conn, "utf8");
// 选择数据库
mysqli_select_db($conn,"mysql8256553_db");
$count=0;
$count=mysqli_query($conn,$sql);
return $count;
}
/*增加方法*/
public static function DBInsert($conn,$sql){
// 设置编码,防止中文乱码
mysqli_set_charset($conn, "utf8");
// 选择数据库
mysqli_select_db($conn,"mysql8256553_db");
$count=0;
$count=mysqli_query($conn,$sql);
if ($count>0){
echo "insert success";
}else{
echo "insert fail";
}
return $count;
}
/*修改方法*/
public static function DBUpdate($conn,$sql){
// 设置编码,防止中文乱码
mysqli_set_charset($conn, "utf8");
// 选择数据库
mysqli_select_db($conn,"mysql8256553_db");
$count=0;
$count=mysqli_query($conn,$sql);
return $count;
}
}
2.调用方式
include "../../utils/DBUtils.php";
$conn= DBUtil::DBConnect();
$sql= "select * from mysql8256553_db.tools";
$result=DBUtil::DBSelect($conn,$sql);
DBUtil::DBClose($conn);
直接调用插入、删除、更新,传入sql语句 就ok
然后就对result进行处理遍历
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['web_title'] . "</td>";
echo "<td>" . $row['web_use'] . "</td>";
echo "<td><a href='".$row['web_url']."' >" . $row['web_url'] . "</a></td>";
echo "</tr>";
}