php mysqli数据库面向过程,面向对象实例比较

<?php
//面向过程
//连接数据库
$mysqli=mysqli_connect('localhost','root','root','test');
if(!$mysqli){
    die("连接失败".mysqli_connect_error($mysqli));
}
// 设置数据库编码
mysqli_query($mysqli,"set names utf8");
//进行查询工作
$sql="select * from user1";
$res=mysqli_query($mysqli,$sql);
//处理结果
while($row=mysqli_fetch_row($res)){
    foreach($row as $key=>$value)
        echo "--$value";
    echo "<br>";
}
//释放资源
mysqli_free_result($res);
//关闭数据库
mysqli_close($mysqli);
?>

<?php
//mysqli面向对象风格
//1。创建mysql对象
$mysqli=new mysqli("localhost","root","root","test");
if($mysqli->connect_error){
    die("连接失败".$mysqli->connect_error);
}
$mysqli->query("utf8");
//2。操作数据库
$sql="select * from user1";
$res=$mysqli->query($sql);
//3。处理结果
while($row=$res->fetch_row())
{
    foreach($row as $key=>$value)
        echo "--$value";
    echo "<br>";
}
//4。关闭资源
$res->free();
$mysqli->close();
?>

猜你喜欢

转载自blog.csdn.net/zch3210/article/details/77099449