主要分为两种,一是通过MYSQLI方式,另外是通过PDO
MYSQLI方式只能连接mysql数据库,而PDO方式可以连接12种数据库,便于数据库切换
一、MYSQLI方式
分为面向过程和面向对象两种不同的方式
1.MYSQLI(面向过程)
<?php
$servername = "localhost";
$username="root";
$password="";
//创建连接
$conn=mysqli_connect($servername,$username,$password);
if(!$conn){
die("Connection failed:".mysqli_connect_error());
}
echo "连接成功!";
//关闭连接
mysqli_close($conn);
echo "<br>"."连接已关闭";
echo "<br>";
?>
2.MYSQLI(面向对象)
<?php
/**
* Created by PhpStorm.
* User: 恒信科技
* Date: 2019/5/18
* Time: 16:53
*/
$servername = "127.0.0.1";
$username = "root";
$password = "";
$conn = new mysqli($servername,$username,$password);
if ($conn->connect_error) {
die("Connection failed:" + $conn->connect_error);
}
echo "连接成功"."<br>";
//关闭连接
$conn->close();
echo "连接已经关闭";
echo "<br>";
?>
二、PDO方式
<?php
/**
* Created by PhpStorm.
* User: 恒信科技
* Date: 2019/5/18
* Time: 16:53
*/
$servername = "localhost";
$username = "root";
$password = "";
try{
$conn=new PDO("mysql:host=$servername;",$username,$password);
echo "连接成功!"."<br>";
}
catch (PDOException $e){
echo $e->getMessage();
}
//关闭连接
$conn=null;
echo "连接已经关闭"."<br>";
?>