我对PDO相当新,早些时候我总是使用mysql
或mysqli
但我通过在线阅读文章以某种方式了解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_by
和PDO
复杂查询?
谢谢!
答案 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() );