为什么PDO没有连接到数据库

时间:2016-09-16 08:54:03

标签: php mysql pdo

我对PDO相当新,早些时候我总是使用mysqlmysqli但我通过在线阅读文章以某种方式了解PDO,最后我生成了这个commen脚本来连接数据库。
这是我自己编写的完整代码。

<?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';
 }
?>  

现在首先这个脚本不起作用,我也想问一些问题 1.为什么我需要将此数据库try catch块绑定到function
2.我如何使用order_by执行group_byPDO复杂查询?

谢谢!

1 个答案:

答案 0 :(得分:0)

检查您是否安装了带有PD的PDO扩展程序
执行命令行: php -m
如果存在,搜索 pdo_mysql

这里有一个ORDER BY&amp;通过...分组:

    $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() );