如果我想将连接放在外部文件中,该代码的哪一部分应该在该外部文件中?
$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;
答案 0 :(得分:1)
此部分将包含外部文件,例如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);
?>
然后你的代码看起来像
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;
答案 1 :(得分:0)
$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);
}
直到此部分可以转到外部文件,并可用于在需要时打开连接。