php基础-mysqli

时间:2022-06-01 21:42:33

基本八个步骤

//连接数据库
$link = mysqli_connect('localhost', 'root', '');

//判断是否连接成功
if (!$link) {
    exit('数据库连接失败');
}

//设置字符集
mysqli_set_charset($link, 'utf8');

//选择数据库
mysqli_select_db($link, 'test');

//准备sql
$sql = 'select * from users';

//查询
$res = mysqli_query($link, $sql);

//处理结果集
$result = mysqli_fetch_assoc($res);

//关闭连接,释放资源
mysqli_close($link);

处理结果集的一些函数

//返回第一条关联数组
$rows = mysqli_fetch_assoc($res);
//返回第一条索引数组
$result = mysqli_fetch_row($res);
//返回第一条关联及索引数组
$result = mysqli_fetch_array($res);
//返回结果集行数
$result = mysqli_num_rows($res);
//返回受影响行数
$result = mysqli_affected_rows($link);
//返回插入的自增id
$result = mysqli_insert_id($link);

mysqli的面向对象写法

//$link = mysqli_connect('localhost', 'root', '');
$mysqli = new mysqli('localhost', 'root', '');
//if (!$link) {
//    exit('数据库连接失败');
//}
if ($errMsg = $mysqli->connect_error) {
    exit($errMsg);
}

//mysqli_set_charset($link, 'utf8');
$mysqli->set_charset('utf8');

//mysqli_select_db($link, 'test');
$mysqli->select_db('test');

$sql = 'select * from users';

//$res = mysqli_query($link, $sql);
$res = $mysqli->query($sql);
//$result = mysqli_fetch_assoc($res);
//返回
while ($rows = $res->fetch_assoc()) {
    echo $rows['username'].'<br>';
}

$mysqli->close();