The steps to establish a PHP database connection include: Configuring PHP and the database using the mysqli extension: $conn = new mysqli($servername, $username, $password, $dbname) Using PDO: $conn = new PDO("mysql:host =$servername;dbname=$dbname", $username, $password)
How to establish a PHP database connection from scratch
Step 1: Configure PHP and database
Step 2: Use the mysqli extension
PHP provides the mysqli extension to connect to and operate the MySQL database. Use the following code:
$servername = "localhost"; $username = "root"; $password = "mypassword"; $dbname = "mydatabase"; try { // 创建一个新的 mysqli 连接对象 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { throw new Exception($conn->connect_error); } // 执行查询 $result = $conn->query("SELECT * FROM mytable"); // 处理查询结果 while ($row = $result->fetch_assoc()) { echo $row['id'] . " - " . $row['name'] . "<br>"; } // 关闭连接 $conn->close(); } catch (Exception $e) { echo $e->getMessage(); }
Step 3: Use PDO
PHP Data Objects (PDO) provide a database-independent interface. Use the following code:
try { // 创建一个新的 PDO 连接对象 $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 设置 PDO 错误模式 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 执行查询 $stmt = $conn->prepare("SELECT * FROM mytable"); $stmt->execute(); // 处理查询结果 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $row['id'] . " - " . $row['name'] . "<br>"; } // 关闭连接 $conn = null; } catch (PDOException $e) { echo $e->getMessage(); }
Practical case: Establishing a connection to the MySQL database
// 使用 mysqli 扩展 $conn = new mysqli("localhost", "root", "mypassword", "mydatabase"); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 执行查询 $result = $conn->query("SELECT * FROM users"); // 获取查询结果 $users = $result->fetch_all(MYSQLI_ASSOC); // 循环遍历结果 foreach ($users as $user) { echo $user['id'] . " - " . $user['username'] . "<br>"; }
The above is the detailed content of How to establish a PHP database connection from scratch. For more information, please follow other related articles on the PHP Chinese website!