<?php
$host_name = "localhost";
$database = "pdo"; // Change your database name
$username = ""; // Your database user id
$password = ""; // Your password
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Here the variables $host_name is the name of the MySQL server host or ip address ( 'localhost' or '127.0.0.1')require "config.php";
Connecting to a PostgreSQL database with PDO is similar to MySQL but requires a different DSN. Here’s an example:
<?php
try {
$dbo = new PDO('pgsql:host=localhost;dbname=testdb', 'username', 'password');
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successful!";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
It’s possible to define a connection timeout by setting the ATTR_TIMEOUT attribute:
<?php
$dbo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
$dbo->setAttribute(PDO::ATTR_TIMEOUT, 5); // Timeout set to 5 seconds
?>
Persistent connections improve performance by reusing the same connection rather than opening a new one each time:
<?php
$dbo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password', array(
PDO::ATTR_PERSISTENT => true
));
?>
Handling connection errors in a structured way helps improve user experience and debugging:
<?php
try {
$dbo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successful!";
} catch (PDOException $e) {
error_log("Connection failed: " . $e->getMessage()); // Log the error
echo "Database connection could not be established.";
}
?>
<?Php
$host_name = "34.68.103.244";
$database = "my_tutorial"; // Change your database name
$username = "root-plus2net"; // Your database user id
$password = "************"; // Your password
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
/// Sample script to display records ////
$sql="select * from student ";
echo "<table>";
foreach ($dbo->query($sql) as $row) {
echo "<tr ><td>$row[name]</td></tr>";
}
echo "</table>";
?>
Details of MySQL database setupDownload Zip file to test your PHP PDO script
PDO ReferencesPDO Fetch record
02-10-2021 | |
cant we connect to a phpmyadmin sql database? |