PHP MySQL PDO stands for PHP Data Objects. It is a PHP extension that provides a lightweight and consistent interface for accessing databases in PHP. PDO supports multiple database drivers, including MySQL, PostgreSQL, SQLite, and more.
Using PDO, you can connect to a MySQL database and perform various database operations such as querying data, inserting data, updating data, and deleting data. PDO provides a set of methods and classes to handle these operations in a secure and efficient manner.
Here is an example of connecting to a MySQL database using PDO:
// Database credentials
$host = 'localhost';
$dbName = 'mydatabase';
$username = 'root';
$password = 'mypassword';
// Create a new PDO instance
$dsn = "mysql:host=$host;dbname=$dbName";
$pdo = new PDO($dsn, $username, $password);
// Query data from the database
$stmt = $pdo->query('SELECT * FROM users');
while ($row = $stmt->fetch()) {
echo $row['username'] . ', ' . $row['email'] . '<br>';
}
// Insert data into the database
$stmt = $pdo->prepare('INSERT INTO users (username, email) VALUES (?, ?)');
$stmt->execute(['john', 'john@example.com']);
// Update data in the database
$stmt = $pdo->prepare('UPDATE users SET email = ? WHERE id = ?');
$stmt->execute(['newemail@example.com', 1]);
// Delete data from the database
$stmt = $pdo->prepare('DELETE FROM users WHERE id = ?');
$stmt->execute([1]);
In this example, we first create a new PDO instance by passing the database credentials to the PDO constructor. Then, we can use various PDO methods such as query(), prepare(), and execute() to perform database operations.
Note that using PDO with prepared statements helps prevent SQL injection attacks by automatically escaping user input. It also provides additional security features such as parameter binding and data type handling.
上一篇:php加载mysql模块?(php安装mysql扩展模块)
下一篇:mysql
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站