I'm aware that Mysql is not preffered for obvious reasons, but It's not my decision to continue using it.
<?php
if (!mysql_select_db('dobhost_databaseexamplename', $con)) {
echo 'Could not select database';
exit;
}
$sql = ("SELECT * FROM sections WHERE recid = '" .$page. "'");
$result = mysql_query($sql, $con);
if (!$result) {
echo "DB Error, could not query the database
";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
?>
<title>Carpets - <?php echo $row['title'];?></title>
<meta name="description" content="<?php echo $row['descr'];?>" />
<meta name="keywords" content="<?php echo $row['keywords'];?>" />
<?php
}
mysql_free_result($result);
?>
this code works fine as an include, its database connection is set up elsewhere but it all works fine, the only issue is that when i include it into the template header, it breaks all the php code below it - Is there any way to isolate my query and php echos so that they won't affect the content below?
Many thanks!
Wrap it in a function, you may be defining vars, which are are used later on in another script.
Also the loop might be a bad idea, you could end up with multiple title elements.
echo 'Could not select database';
exit;
This is bad too, just throw an exception like this: throw new \Exception('Could not select database');
<?php
function getMetaTags($pageId) {
global $con;
if (!mysql_select_db('dobhost_databaseexamplename', $con)) {
throw \Exception('Error selecting db');
}
$sql = (sprintf("SELECT * FROM sections WHERE recid = %d", $pageId));
$result = mysql_query($sql, $con);
if (!$result) {
throw new \Exception(mysql_error(), mysql_errno());
}
if(!$row = mysql_fetch_assoc($result)) {
throw new \Exception(sprintf('Page with id %d not found', $pageId);
}
return sprintf('<title>Carpets - %s</title>
<meta name="description" content="%s" />
<meta name="keywords" content="%s" />', $row['title'], $row['descr'], $row['keywords']);
}
}