Hello.
Please look at this:

<?php
    $servername = "localhost";
    $dbname = "mydbname";
    $dbusername = "mydbusername";
    $dbpassword = "mydbpassword";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $id=$_GET['id'];

        $sql = "DELETE FROM Posts WHERE ID = :id";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':id', $id, PDO::PARAM_STR);
        $stmt->execute();
        header("location: admin.php");
    } catch(PDOException $e) {
        echo $sql . "<br>" . $e->getMessage();
    }            
    $conn = null;
?>

I see some tutorial examples put this part in a for example "connection.php" file:

        <?php
        $servername = "localhost";
        $dbname = "mydbname";
        $dbusername = "mydbusername";
        $dbpassword = "mydbpassword";

        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        ?>

and then using include(connection.php); in their php files. Now if you look at my code above, you see there is this line in it:

        try {

So, what should i do? Can i forget to use try-catch in my scripts? If not so how can i put that part of code in the connection.php file to use with include()?

Can i put this:

    <?php
        $servername = "localhost";
        $dbname = "mydbname";
        $dbusername = "mydbusername";
        $dbpassword = "mydbpassword";

        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

in the connection.php file while the try block left open?! and be closed in the other php files?

Dani AI

Generated

Short answer: a try/catch must form a syntactically complete statement in the final PHP code. Because include() literally inserts file contents, it is technically possible to start a try { in one file and close it in another, but that is fragile, hard to read, and will break as soon as includes change. The safe, maintainable approaches are either (A) let the connection code throw exceptions and catch them where the script runs, or (B) make the connection file handle its own errors and expose a valid PDO object (or fail fast).

's idea of putting connection logic in a single file is good — but prefer one of these patterns:

  • Export a factory function or class that returns a PDO instance (no open try across files). The caller wraps calls that belong together in its own try/catch.
  • Or, let the connection file catch connection errors and handle them centrally (log, show a generic error page, or rethrow). Avoid echoing raw $sql or $e->getMessage() to users; log them instead.

Example factory pattern (keeps try/catch local to the caller):

<?php
function dbConnect() {
    $dsn = 'mysql:host=localhost;dbname=app;charset=utf8mb4';
    $opts = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ];
    return new PDO($dsn, DB_USER, DB_PASS, $opts);
}

Caller code then wraps use in try/catch and logs failures.

Practical tips and cautions: validate inputs (use filter_input(..., FILTER_VALIDATE_INT) for numeric ids), bind with the correct PDO param type (e.g. PDO::PARAM_INT for integers), call exit after header('Location: ...'), and avoid printing SQL or exception messages to users. For troubleshooting, confirm DSN, credentials, and that the PDO MySQL driver is installed — the credential mistake noted by is a common cause of connection errors.

Recommended Answers

All 6 Replies

Member Avatar for Member #120589

The whole point (IMO) of try is to catch an exception when things go wrong. If you're not using a catch then why do you need a try?

Think carefully about howw you use Exceptions in production code. Exceptions are different to errors, but there are methods of combining them to give a consistent output, if you need to. Production uses could include writing to logs etc.

Wonder if I get the question correctly, you wish to seperate your full code into conn.php but wonder on how to made the try catch block to seperate itself? If so, try to understand what you wish to accomplish and try to understand the codes you written. If I am in the case, I will put into conn.php

<?php
    $servername = "localhost";
    $dbname = "mydbname";
    $dbusername = "mydbusername";
    $dbpassword = "mydbpassword";
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        //here will only display the connection error
        echo "Database connection error:" . $sql . "<br>" . $e->getMessage();
    }
?>

Then my code in my main script will be

<?php
    include('conn.php');
    try {
        $id=$_GET['id'];
        $sql = "DELETE FROM Posts WHERE ID = :id";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':id', $id, PDO::PARAM_STR);
        $stmt->execute();
        header("location: admin.php");
    } catch(PDOException $e) {
        echo "Query error:".$sql . "<br>" . $e->getMessage();
    }            
    $conn = null;
?>
commented: Ah. Now I get the question +15

Thank you . I understood. I will do what you recommend to me.

i used that way but faced mhith some errors.

Can you goes detail on what error you get? As far as I know, the echo "Database connection error:" . $sql . "<br>" . $e->getMessage(); and echo "Query error:".$sql . "<br>" . $e->getMessage(); most probably not work as we wish, as $sql is not defined but those messages I simply shows as example. Please do understand and implement your own. Or there are other errors occurs, can you elaborate more on them?

Oh! i'm sorry i found the problem. I forgot to change this part:

$servername = "localhost";
$dbname = "mydbname";
$dbusername = "mydbusername";
$dbpassword = "mydbpassword";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.