Connection new pdo
Here is an example of how to connect to a database using PDO (PHP Data Objects):
Step 1: Create a PDO instance
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'myusername';
$password = 'mypassword';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: '. $e->getMessage();
exit();
}
In this example, we're creating a PDO instance with the following parameters:
$dsn
: the data source name, which includes the database type (mysql), host (localhost), and database name (mydatabase).$username
: the username to use for the connection.$password
: the password to use for the connection.
Step 2: Set the PDO attributes
You can set various PDO attributes to customize the connection behavior. For example, you can set the error mode to throw exceptions instead of displaying errors:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Step 3: Execute a query
Once you have a PDO instance, you can execute a query using the query()
method:
$stmt = $pdo->query('SELECT * FROM mytable');
In this example, we're executing a SELECT query that retrieves all rows from a table named mytable
.
Step 4: Fetch the results
You can fetch the results of the query using the fetchAll()
method:
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
In this example, we're fetching all rows from the query result as an associative array.
Full example
Here is the full example:
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'myusername';
$password = 'mypassword';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->query('SELECT * FROM mytable');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
echo $row['column1']. ' - '. $row['column2']. "\n";
}
} catch (PDOException $e) {
echo 'Connection failed: '. $e->getMessage();
exit();
}
This example connects to a MySQL database, executes a SELECT query, and fetches the results as an associative array. It then prints out the values of two columns from each row in the result set.