PDO Database Connect – PDO Database bağlantı – PDO Bağlantısı
PDO (PHP Data Objects) is a PHP extension for accessing databases. It provides a consistent and object-oriented way to interact with various database systems, including MySQL, PostgreSQL, SQLite, Oracle, and Microsoft SQL Server.
Here’s an example of how to connect to a MySQL database using PDO:
try {
$dsn = 'mysql:host=localhost;dbname=mydb';
$username = 'myuser';
$password = 'mypass';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $username, $password, $options);
// Your database code here
} catch (PDOException $e) {
// Handle errors
echo 'Error: ' . $e->getMessage();
}
In this example, we’re connecting to a MySQL database named mydb
on the localhost. We’re also setting some options for the PDO instance, such as the error mode and fetch mode.
Here’s a breakdown of the code:
- We start by trying to connect to the database using the
try
block. - We define the DSN (Data Source Name) string, which includes the database driver and connection details. In this case, we’re using the
mysql
driver for MySQL. - We set the username and password for the database.
- We define an array of options for the PDO instance. Here, we’re setting the error mode to
PDO::ERRMODE_EXCEPTION
, which will throw an exception if there’s an error. We’re also setting the default fetch mode toPDO::FETCH_ASSOC
, which will return the result set as an associative array. Finally, we’re disabling emulation of prepared statements, which is recommended for better performance. - We create a new PDO instance using the
new
keyword and passing in the DSN, username, password, and options. - If there’s an error connecting to the database, the
catch
block will be executed, and we’ll print out the error message. - If the connection is successful, we can use the PDO instance to execute queries and fetch data.
By using PDO, we can write more consistent and portable database code that’s easier to maintain and debug.