1、连接数据库
2、执行SQL语句
3、PHP数据库操作详解
在当今的Web开发中,数据库已经成为了不可或缺的一部分,PHP作为一种流行的服务器端脚本语言,其对数据库的操作也变得越来越重要,本文将详细介绍PHP中与数据库相关的操作,包括连接数据库、执行SQL语句、处理结果集等,希望通过这篇文章,能够帮助大家更好地理解和掌握PHP数据库操作。
1. 连接数据库
要使用PHP进行数据库操作,首先需要建立与数据库的连接,在PHP中,可以使用mysqli或PDO扩展来实现这一功能,下面分别介绍这两种方法:
1.1 使用mysqli扩展连接MySQL数据库:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } echo "连接成功"; $conn->close(); ?>
1.2 使用PDO扩展连接MySQL数据库:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 设置 PDO 错误模式为异常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "连接成功"; } catch(PDOException $e) { echo "连接失败: " . $e->getMessage(); } $conn = null; ?>
2. 执行SQL语句
在建立了与数据库的连接之后,就可以开始执行SQL语句了,在PHP中,可以使用mysqli_query()函数或PDOStatement对象来执行SQL语句,下面分别介绍这两种方法:
2.1 使用mysqli扩展执行SQL语句:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "INSERT INTO MyTable (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
2.2 使用PDO扩展执行SQL语句:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 设置 PDO 错误模式为异常 the prepared statement with a value of variable 'firstname' and return it by reference . The second parameter uses a named placeholder (?). The third parameter uses another named placeholder (?).""); // set parameters and execute this prepared statement You can also use positional parameters to represent the values to be inserted. However, when using positional parameters you must specify an array or collection of values that matches the number of parameters in your SQL statement. This is done using a call to bindValue(). This method binds a value to a parameter, and makes that parameter available for use by prepared statements. When you prepare your statement with bindValue(), you can then pass the parameter names to the bindParam() method as arguments. To see how to use bindValue() and bindParam() together with a prepared statement, read the following example carefully.""); // execute the prepared statement this will insert a record into MyTable and return its ID value into a variable called 'lastInsertId'.</pre>
还没有评论,来说两句吧...