I'm fairly new to PDO, earlier I always used mysql
or mysqli
but I somehow learned about PDO by reading articles online and finally I generated this commen script to connect from database.
Here is my complete code which I wrote myself.
<?php
function connection() {
try {
$host = "localhost";
$charset = "utf8";
$user = "my_username";
$pass = "my_pass";
$db = "my_db_name";
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$conn = new PDO ($dsn, $user, $pass, $options);
} catch (PDOException $e) {
$output = "We are unable to connect from database";
$file = "error_log.php";
$err_msg = $e->getMessage() " This error occured on <?php echo date("d/m/y i:m:s A");?>";
file_put_contents($file, $err_msg);
include 'inc/script-error.php';
}
$output = "Connection with database was successfull.";
include 'inc/script-success.php';
}
?>
Now first of all this script is not working and I also want to ask some questions
1. Why I need to bind this database try
catch
block into a function
?
2. How I perform order_by
and group_by
complex queries with PDO
?
Thanks!