小兔网

连接mysqli 查询

//面向对象的方法
<?php
//连接数据库
$con = new mysqli('host','username','password','db_name','port');

if(mysqli_connect_errno()){
echo '数据库连接错误!错误信息是:'.mysqli_connect_error();
exit;
}

//准备SQL语句
$sql = 'select * from table';

//执行SQL语句
$query = $con->query($sql);

while($row = $query->fetch_array()){
echo $row['id'],'<br>';
}

//释放资源
$query->close();

//关闭连接
$con->close();
?>

 

<?php
//连接数据库
$con = mysqli_connect('host','user','password','database','port');

//判断是否连接成功
if(!$con){
echo "数据库失败!";
}

//准备sql语句
$sql = "select * from table";

//执行sql语句
$query = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($query)){
echo $row['id'].'<br>';
}

//释放资源
mysqli_free_result($query);

//关闭连接
mysqli_close($con);
?>