Home >Backend Development >PHP Tutorial >PHP database connection from entry to practical application: master it step by step
Database connection in PHP consists of two phases: creating a connection (using MySQLi or PDO to establish communication with the database server) and executing the query (preparing, binding parameters and executing query statements). In the user registration exercise, bind the user data to the query statement and execute it to insert the new user into the database.
Database The connection is the bridge that establishes communication between the PHP code and the database server.
PHP provides a variety of database drivers, the most commonly used of which are MySQLi and PDO.
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // 创建 MySQLi 连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 使用连接 // ...
$dsn = "mysql:host=localhost;dbname=database_name"; $username = "username"; $password = "password"; // 创建 PDO 连接 $conn = new PDO($dsn, $username, $password); // 检查连接是否成功 if (!$conn) { die("连接失败"); } // 使用连接 // ...
// 准备查询语句 $query = $conn->prepare("SELECT * FROM users"); // 执行查询 $query->execute(); // 获取结果 $result = $query->get_result(); // 遍历结果 while ($row = $result->fetch_assoc()) { echo $row["name"] . "<br>"; }
// 准备查询语句 $stmt = $conn->prepare("SELECT * FROM users"); // 执行查询 $stmt->execute(); // 获取结果 $result = $stmt->fetchAll(PDO::FETCH_ASSOC); // 遍历结果 foreach ($result as $row) { echo $row["name"] . "<br>"; }
// ... 同上连接数据库部分 // 准备查询语句 $stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
// 绑定参数 $name = "John Doe"; $email = "john.doe@example.com"; $password = "securepassword"; $stmt->bind_param("sss", $name, $email, $password); // 执行查询 $stmt->execute();
The above is the detailed content of PHP database connection from entry to practical application: master it step by step. For more information, please follow other related articles on the PHP Chinese website!