Search code examples
phpsql-serverpdometa-tagsmeta

Change meta description/keywords dynamically with php


Im trying to grab some info from the db and use it as meta desc and keyword. But something isnt working as it supposed to.

EDIT: after alot of help i got it semi working. If there is no blogID i want it to fallback on the other part... that part of the script aint working, any ideas?

<?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"; 
}

?>

Solution

  • It might not be the prettiest code... but it works!

    <?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'; ?>">