-1

My try:

1st File (connopen.php)

<?php
    try {
        $db = new PDO(DB_DSN, DBUSER, DB_PASSWORD);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    } catch (PDOException $e) {
        die('Cannot connecto to database!');
    }

    try {
        $db->beginTransaction();

Other Files (file1.php, file2.php ...)

<?php
    include('connopen.php');

    ...some code using SQL(SELECT, INSERT INTO, UPDATE, DELETE ....)

    include('connclose.php');
?>

Last File (connclose.php)

<?php
        $db->commit();
    } catch (PDOException $e) {
        $db->rollBack();
        ..some code to log errors
    }
    $db = null;
?>

This as is, throws an Error (Parse error: syntax error, unexpected $end in /connopen.php on line 11) because I start try { on connopen.php and I closed on connclose.php

If there is another way to do something like that to prevent double-triple coding... of connopen and connclose source code will appreciate. thanks

4

2 回答 2

1

Sure.
Just get rid of connclose.php, transactions and try..catches - you don't need them.
So, the code become plain and simpke

1st File (connopen.php)

<?php
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
);
$db = new PDO(DB_DSN, DBUSER, DB_PASSWORD, $opt);

Other Files (file1.php, file2.php ...)

<?php
    include('connopen.php');

    ...some code using SQL(SELECT, INSERT INTO, UPDATE, DELETE ....)
于 2013-04-14T16:39:38.333 回答
1

由于破坏了 try 语句,您的语法有严重错误。

连接文件应该只是

  <?php
    try {
        $db = new PDO(DB_DSN, DBUSER, DB_PASSWORD);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    } catch (PDOException $e) {
        die('Cannot connecto to database!');
    }

正确的模式是创建一个带有应用程序引导(设置、数据库和外部服务连接等)的文件,该文件根据 URL 解析结果将脚本执行路由到不同的 php 脚本(file1.php、file2.php)。

于 2013-04-14T16:38:12.227 回答