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?