Use PHP Data Objects (PDO) to establish object-oriented PHP database connections, providing a unified interface for interacting with various databases. The establishment of a PDO connection requires a data source name (DSN), username and password. Use the query() method to execute SQL queries and the fetchAll() method to obtain results. Practical examples show how to connect a PHP form to a MySQL database and insert data.
Use PDO to establish an object-oriented PHP database connection
Object-oriented PHP database connection uses the PHP Data Object (PDO) class Library that provides a unified interface for interacting with various databases. Using PDO, you access the database in an object-oriented manner, which makes the code easier to organize and maintain.
Establishing a PDO connection
To establish a PDO connection, you need to use the PDO
constructor. This constructor accepts the following parameters:
$dsn = 'mysql:host=localhost;dbname=my_database'; $username = 'root'; $password = ''; try { $pdo = new PDO($dsn, $username, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); die(); }
Execute query
You can use the query()
method to execute a SQL query. This method returns a PDOStatement object that represents the query results.
$sql = 'SELECT * FROM users WHERE name LIKE ?'; $stmt = $pdo->prepare($sql); $stmt->execute(['%joh%']);
Get the results
You can get the query results through the fetchAll()
method. This method returns a result array where each element is an associative array.
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
Practical Example
Consider a basic PHP form where a user can enter their name and insert it into a database. We use PDO to connect this form to a MySQL database.
<!-- form.php --> <form action="submit.php" method="post"> <label for="name">姓名:</label> <input type="text" id="name" name="name"> <input type="submit" value="提交"> </form>
// submit.php $dsn = 'mysql:host=localhost;dbname=my_database'; $username = 'root'; $password = ''; try { $pdo = new PDO($dsn, $username, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); die(); } $name = $_POST['name']; $sql = 'INSERT INTO users (name) VALUES (?)'; $stmt = $pdo->prepare($sql); $stmt->execute([$name]); header('Location: success.php');
<!-- success.php --> <h1>成功!</h1> <p>您的姓名已添加到数据库中。</p>
This example demonstrates how to use PDO to connect a PHP form to a MySQL database and insert data.
The above is the detailed content of Establish object-oriented PHP database connection using PDO. For more information, please follow other related articles on the PHP Chinese website!