一共7步,下面详细说明
1、链接数据库服务器
//参数1:数据库所在服务器的域名
//参数2:登录数据库的用户名
//参数3:登录数据库的密码
$con = mysqli_connect("localhost:3306","root","")
or die(mysqli_connect_error());
//die终止程序代码执行,并输出错误信息
2、选择要链接的数据库
$dataBase = mysqli_select_db($con,"zzq1802")
or die(mysqli_connect_error());
3、设置编码格式
$dataBase = //mysqli_query:执行语句
mysqli_query($con,"set names utf8");
4、编写sql语句
$sql = "SELECT * FROM student";
5、执行sql语句, 并接收执行结果
$result = mysqli_query($con,$sql);
6、把结果放进数组
$arr = array();
while($row = mysqli_fetch_assoc($result)){
array_push($arr,$row);
}
7、把从数据库中取到的结果返回给前端
$arr = array();
echo json_encode($arr);
最后附上一个封装好的链接后台数据库的代码块
<?php
/**
* Created by PhpStorm.
* User: ganggang
* Date: 2018/9/25
* Time: 21:14
*/
function connectDB($ip,$user,$pass,$db){
$con = mysqli_connect($ip,$user,$pass) or die(mysqli_connect_error());
mysqli_select_db($con,$db);
mysqli_query($con,"set names utf8");
return $con;
}
function sel($con,$sql){
$result = mysqli_query($con,$sql);
$arr = array();
while($row = mysqli_fetch_assoc($result)){
array_push($arr,$row);
}
return $arr;
}
function cha($con,$sql){
mysqli_query($con,$sql);
if (mysqli_affected_rows($con) > 0){ // 数据表数据受影响的行数
return true; // 执行成功
} else {
return false;
}
}