douyou1901 2014-10-04 18:57
浏览 35

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

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!

  • 写回答

1条回答 默认 最新

  • douliaodun9153 2014-10-04 19:05
    关注

    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']);
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法