PHP5以及版本使用允许以下方式连接MYSQL:
- MYSQLi extension
- PDO(PHP Data Objects)
1. 连接MYSQL
// MYSQLi-面向对象
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// 创建连接
$conn = new mysqli($sername,$username,$password);
if ($conn->connect_error)
{
die("连接失败:" . $conn->connect_error);
}
echo "连接成功";
// 关闭连接
$conn->close();
?>
MYSQLi-面向过程
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// 创建连接
$conn = mysqli_connect($servername,$username,$password);
// 检测连接
if(!conn)
{
die("Connection failed: " . mysqli_connect_error());
}
echo "连接成功";
// 关闭连接
mysqli_close($conn);
?>
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;",$username,$password);
echo "连接成功";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$conn = null;
?>
2. 创建数据库
MYSQLi-面向对象
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername,$username,$password);
if ($conn->connect_error)
{
die("连接失败:" . $conn->connect_error);
}
$sql = "create database mytest";
if($conn->query($sql) === TRUE)
{
echo "数据库创建成功";
}
else {
echo "连接失败:" . $conn->error;
}
$conn->close();
?>
MYSQLi-面向过程
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_conncet($servername,$username,$password);
if (!$conn)
{
die("连接失败:" . mysqli_connect_error());
}
$sql = "create database mytest";
if (mysqli_query($conn,$sql))
{
echo "数据库创建成功!";
}else {
echo "数据库创建失败:" . mysqli_error($conn);
}
mysqli_close($conn);
?>
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysqli:host=$servername",$username,$password);
// 设置PDO错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql = "create database mytest";
// 使用exec(),因为没有返回结果
$conn->exec($sql);
echo "数据库创建成功<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
//php7
mysqli_query($conn, "set character set 'utf8'");//读库
mysqli_query($conn,"set names 'utf8'");//写库
//php5
mysql_query("set character set 'utf8'");//读库
mysql_query("set names 'utf8'");//写库
3. 创建数据表
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
$conn = new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error)
{
die("连接失败:" . $conn->conncet_error);
}
$sql = "create table myguest(
id int(19) unsigned auto_increment primary key,
firstname varchar(30) no null,
lastname varchar(30) no null,
email varchar(50),
reg_date timestamp
)";
if ($conn->query($sql) === TRUE)
{
echo "Tabl myguest created successfully";
} else {
echo "创建表失败:" . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检测连接
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
// 使用 sql 创建数据表
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "数据表 MyGuests 创建成功";
} else {
echo "创建数据表错误: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式,用于抛出异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 使用 sql 创建数据表
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
// 使用 exec() ,没有结果返回
$conn->exec($sql);
echo "数据表 MyGuests 创建成功";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
- 插入数据
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检测连接
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($conn, $sql)) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式,用于抛出异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
// 使用 exec() ,没有结果返回
$conn->exec($sql);
echo "新记录插入成功";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql = "insert intp myguests(firstname,lastname,email)values('John','Doe','[email protected]')";
$conn->exec($sql);
echo "新建立插入成功";
}
catch (PDOException $e)
{
echo $sql . "<br>" .$e->getMessage();
}
$conn = null;
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
// 创建链接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查链接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";
if ($conn->multi_query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
// 创建链接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检查链接
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";
if (mysqli_multi_query($conn, $sql)) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 开始事务
$conn->beginTransaction();
// SQL 语句
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')");
// 提交事务
$conn->commit();
echo "新记录插入成功";
}
catch(PDOException $e)
{
// 如果执行失败回滚
$conn->rollback();
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
5. 预处理
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
} else {
$sql = "INSERT INTO MyGuests(firstname, lastname, email) VALUES(?, ?, ?)";
// 为 mysqli_stmt_prepare() 初始化 statement 对象
$stmt = mysqli_stmt_init($conn);
//预处理语句
if (mysqli_stmt_prepare($stmt, $sql)) {
// 绑定参数
mysqli_stmt_bind_param($stmt, 'sss', $firstname, $lastname, $email);
// 设置参数并执行
$firstname = 'John';
$lastname = 'Doe';
$email = '[email protected]';
mysqli_stmt_execute($stmt);
$firstname = 'Mary';
$lastname = 'Moe';
$email = '[email protected]';
mysqli_stmt_execute($stmt);
$firstname = 'Julie';
$lastname = 'Dooley';
$email = '[email protected]';
mysqli_stmt_execute($stmt);
}
}
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
$conn = new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error){
die("连接失败:" . $conn->connect_error);
}
// 预处理及绑定
$stmt = $conn->prepare("insert into myguest(firstname,lastname,email)values(?,?,?)");
$stmt->bind_param('sss',$firstnam,$lastnam,$email);
// 设置参数并执行
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "[email protected]";
$stmt->execute();
echo "新记录插入成功";
$stmt->close();
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 预处理 SQL 并绑定参数
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// 插入行
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt->execute();
// 插入其他行
$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt->execute();
// 插入其他行
$firstname = "Julie";
$lastname = "Dooley";
$email = "[email protected]";
$stmt->execute();
echo "新记录插入成功";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
说明:
"INSERT INTO MyGuests (firstname, lastname, email) VALUES(?, ?, ?)"
在SQL语句中,我们使用了问号,在此我们可以将问号替换为整数,字符串,双精度浮点型和布尔值。接下来:
$stmt->bind_param("sss", $firstname, $lastname, $email);
绑定SQL参数,且告诉数据库参数的值。"sss"为参数处理的数据类型。参数有以下四种类型:
- i-integer(整型)
- d-double(双精度浮点型)
- s-string(字符型)
- b-BLOB
6. 读取MySQL数据
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mytest";
$conn = new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error)
{
die("连接失败:" . $conn->connect_errot);
}
$sql = "select id ,firstname ,lastname from mytest";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
}else{
echo "没有数据!";
}
$conn->close();
?>
<?php
$conn = mysqli_connect("localhost","username","password","database");
if(mysqli_connect_error())
{
echo "连接失败:" . mysqli_connect_error();
}
$result = mysqli_query($conn,"select * from person where firstname='peter'");
while($row = mysqli_fetch_array($result))
{
echo $row['firstname'] . " " . $row['lastName'];
}
?>
<?php
$con=mysqli_connect("localhost","username","password","database");
// 检测连接
if (mysqli_connect_errno())
{
echo "连接失败: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}
mysqli_close($con);
?>
<?php
$con=mysqli_connect("localhost","username","password","database");
// 检测连接
if (mysqli_connect_errno())
{
echo "连接失败: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
mysqli_close($con);
?>
<?php
$con=mysqli_connect("localhost","username","password","database");
// 检测连接
if (mysqli_connect_errno())
{
echo "连接失败: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");
mysqli_close($con);
?>
标签:firstname,lastname,sql,stmt,email,MYSQL,PHP,连接,conn
From: https://www.cnblogs.com/kalixcn/p/17364364.html