PDO. How to put the connection in an external file

2020-05-06 04:07发布

问题:

If I want to put the connection in an external file, what part of this code should be in that external file?

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";

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

    $sql = "UPDATE bookmarks
            SET podcast=122, text='some text'
            WHERE id = 152";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    echo $stmt->rowCount() . " records UPDATED successfully";
}

catch(PDOException $e){
    echo $sql . "<br>" . $e->getMessage();
}

$conn = null;

回答1:

This part will go in external file e.g connection.php

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

and then your code will look like

require("connection.php");

try {

    $sql = "UPDATE bookmarks
            SET podcast=122, text='some text'
            WHERE id = 152";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    echo $stmt->rowCount() . " records UPDATED successfully";
}

catch(PDOException $e){
    echo $sql . "<br>" . $e->getMessage();
}

$conn = null;


回答2:

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast"; 
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}

Till this part can go to external file, and can be used to open a connection where ever required.



标签: php pdo