Before we can do anything with a database, we need to talk to it. And to talk to it, we must make a database connection. Logical, isn’t it?
Solution
Here’s how we connect to a MySQL database on the localhost:
We’d use this code to connect to a SQLite database on the localhost:
And this code will let us connect to a PostgreSQL database on the localhost:
Solution
Here’s how we connect to a MySQL database on the localhost:
<?php
$dsn = 'mysql:host=localhost;dbname=world;';
$user = 'user';
$password = 'secret';
try
{
$dbh = new PDO($dsn, $user, $password);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
$dsn = 'mysql:host=localhost;dbname=world;';
$user = 'user';
$password = 'secret';
try
{
$dbh = new PDO($dsn, $user, $password);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
<?php
$dsn = 'sqlite2:"C:\sqlite\world.db"';
try
{
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
$dsn = 'sqlite2:"C:\sqlite\world.db"';
try
{
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
<?php
$dsn = 'pgsql:host=localhost port=5432 dbname=world user=user ';
$dsn .= 'password=secret';
try
{
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
$dsn = 'pgsql:host=localhost port=5432 dbname=world user=user ';
$dsn .= 'password=secret';
try
{
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
Comment