PHP SQL - 需要隔离,因为它会影响页面的其余部分

时间:2014-10-04 18:57:08

标签: php mysql include isolation

我知道Mysql没有出于显而易见的原因,但我决定继续使用它。

<?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\n";
    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);
?>

这段代码作为一个包工作正常,它的数据库连接在其他地方设置但是一切正常,唯一的问题是当我将它包含在模板头中时,它会破坏它下面的所有php代码 - 有没有隔离我的查询和php回声的方式,以便它们不会影响下面的内容?

非常感谢!

1 个答案:

答案 0 :(得分:0)

将其包装在一个函数中,您可能正在定义变量,稍后将在另一个脚本中使用这些变量。

循环可能也是一个坏主意,你最终可能会有多个标题元素。

echo 'Could not select database';
exit;

这也很糟糕,只需抛出这样的异常: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']);
    }
}