使用 php 动态更改元数据 description/keywords

Change meta description/keywords dynamically with php

我正在尝试从数据库中获取一些信息并将其用作元描述和关键字。但是有些东西没有按预期工作。

编辑:经过大量帮助,我让它半工作了。如果没有 blogID,我希望它回退到另一部分...脚本的那部分不起作用,有什么想法吗?

<?php
$dsn = "sqlsrv:Server=localhost;Database=blog";
$conn = new PDO($dsn, "**********", "********");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$id = $_GET['postID'];
$sql = "SELECT * FROM blog_posts WHERE blogID=:id ORDER BY blogID DESC";
 $stmt = $conn->prepare($sql);
                    $stmt->execute (array($id));
                    while($metta = $stmt->fetch(PDO::FETCH_BOTH) )

if (isset($metta['blogID']) && !empty($metta['blogID'])) { 
$keywords = $metta['keywords']; 
$description = $metta['description']; 
} else { 
$keywords = "blalbalbalblabla"; 
$description = "blabla"; 
}

?>

它可能不是最漂亮的代码...但它确实有效!

<?php
$dsn = "sqlsrv:Server=localhost;Database=blog";
$conn = new PDO($dsn, "*****", "*******");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$id = $_GET['postID'];
$sql = "SELECT * FROM blog_posts WHERE blogID=:id";
 $stmt = $conn->prepare($sql);
                    $stmt->execute (array($id));
                    $metta = $stmt->fetch(PDO::FETCH_BOTH);

if (isset($_GET['postID'])) { 
$keywords = $metta['keywords']; 
$description = $metta['description']; 

}
sqlsrv_close($con);
?>


<meta name="description" content="<?= isset($description) ? $description : 'blablabla'; ?>">
        <meta name="keywords" content="<?= isset($keywords) ? $keywords : 'blablabla'; ?>">