首页 > 数据库 >PHP连接MYSQL的一些操作

PHP连接MYSQL的一些操作

时间:2023-04-29 18:55:45浏览次数:68  
标签:firstname lastname sql stmt email MYSQL PHP 连接 conn

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;
?>
  1. 插入数据

<?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

相关文章

  • MySQL常用数据库语句
    ==数据库==1、创建数据库createdatabase[IFNOTEXISTS]数据库名;2、删除数据库dropdatabase[IFEXISTS]数据库名;3、切换数据库selectdatabase();4、查询数据库showdatabases;————————————————————————————==数据表==1、创建数据表crea......
  • docker 创建mysql及卷挂载
    dockerpullmysql:5.7dockerrun-d-p3307:3306-v/home/mysql/conf:/etc/mysql/conf.d-v/home/mysql/data:/var/lib/mysql-eMYSQL_ROOT_PASSWORD=root--namemysql57mysql:5.7----------------------------------------------d后台运行-p3307:3306端口映射-v......
  • PHP重要知识点
    PHP表单和用户输入PHP中的$_POST和$_GET变量用于检索表单中的信息,比如用户输入。实例:<html><head><metacharset="utf-8"><title>test</title></head><body><formaction="welcome.php"me......
  • mysql: character set
    --https://dev.mysql.com/doc/refman/8.0/en/charset-database.htmlshowvariableslike"character_set_%";CREATEDATABASE`geovindu`CHARACTERSETutf8COLLATEutf8_general_ci;--mysql官方说明文档才知道原来MySQL8.0已经已经把默认字符集升级成ut8mb4了ALTERDA......
  • MySQL中的锁有哪些,作用是什么?
    概述:锁最要是用来实现MySQL的隔离性。我们都知道事务有四大特性分别是:原子性、一致性、隔离性、持久性,即所说的ACID。一、什么是ACID1、原子性:事务中包含有很多操作,这些操作要么全部执行,要么全部不执行,所以支持回滚操作。2、一致性:系统从一种一致性到另一种一致性状态。事物的一致......
  • Flask 中用 dbutils 实现数据库连接池
    Flask中用dbutils实现数据库连接池之前用dbutils来实现数据库连接池,这里将其封装为一个自定义类并在flask中实际应用一下,在实际场景中肯定是多页面接口,这也就涉及到python的import问题,就个人感觉它没有像js那样方便,但也能用吧.目录......
  • 数据库连接池 - Pymysql
    数据库连接池+pymysql最近想用小程序来做个移动BI,然后涉及后端接口部分打算用Python的flask框架整一波,主要听闻它比较轻量,简单和可灵活配置,这就和我很对味.毕竟我主要搞数据用的就是sql而已,只要有个服务器提供接口就行.真正开始来写接......
  • windows连接ubuntu共享文件夹
    安装sambasudoaptinstallsamba编辑配置文件sudovim/etc/samba/smb.conf在末尾加入:[echohye]#smb用户path=/home/echohye/共享文件夹#共享路径available=yeswriteable=yessecurity=sharebrowseable=yesguestok=yesforceus......
  • MySQL日期字符串转日期格式,日期格式数据转为字符串
    如下:1、日期字符串转换为日期格式数据SELECTDATE('2017-02-11');SELECTDATE('2017/02/11');SELECTSTR_TO_DATE('2015/02/25','%Y/%m/%d');SELECTSTR_TO_DATE('2015-02-25','%Y-%m-%d');返回日期格式数据 2、DATE_FORMAT将日期转......
  • MySQL操作
    创建数据库createdatabase[IFNOTEXISTS]数据库名;查询数据库showdatabases;删除数据库dropdatabase[IFEXISTS]数据库名;切换数据库selectdatabase();——————————————————创建数据表createtable表名(字段名1字段类型1(字段长度)......