BİLGİ BANKASI
Bilgi Bankası, Teknik Konular, Videolar
Search for:
  • Home/
  • PDO/
  • PDO Database Connect – PDO Database bağlantı – PDO Bağlantısı

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:

  1. We start by trying to connect to the database using the try block.
  2. 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.
  3. We set the username and password for the database.
  4. 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 to PDO::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.
  5. We create a new PDO instance using the new keyword and passing in the DSN, username, password, and options.
  6. If there’s an error connecting to the database, the catch block will be executed, and we’ll print out the error message.
  7. 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.

Leave A Comment

All fields marked with an asterisk (*) are required