-1

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!

Jaky
  • 47
  • 1
  • 2
  • 9

1 Answers1

0

Check if you have PDO extension installed with php
Exec in command line : php -m
And search for pdo_mysql if exist

Here an example with ORDER BY & GROUP BY:

    $db = new PDO($dsn, $user, $pass);
    $stmt = $db->prepare( "SELECT * FROM table_name WHERE conditions GROUP BY col_name ORDER BY col_name2 ASC;" ) ;
    $stmt->execute();
    var_dump( $stmt->fetchAll() );
ahammar
  • 282
  • 1
  • 14