如何在php标签之间创建一个类

时间:2016-01-29 15:21:21

标签: php html function class pdo

我有两个函数,每个函数在functions.php文件中包含一个PDO对象,该文件输出html并在另一个文件中调用。我正在尝试组织我的代码并将我的数据库信息放在这些函数之外并将它们用作全局变量。

我已经读过使用全局变量是不好的做法所以我虽然有一个内部有两个函数的类,但是因为在函数之间有html,我发现如果它甚至可能很难将它们放在类中。我可以用我的代码证明最好的方法。我怎样才能在课堂上组织这个?

<?php 

    $hostname = 'host';
    $db = 'database';
    $user = 'username';
    $pass = 'password';

?>

<?php function connectDB () {

    global $hostname, $db, $user, $pass;

    $dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

    $sql = "query 1";

    $query = $dbh->prepare($sql);
    $query->execute(array(//'placeholder',//'placeholder')); 
    $query->setFetchMode(PDO::FETCH_ASSOC); 

        while ($r = $query->fetch()): 

            $variable1 = $r['column1']; 
            $variable2 = $r['column2'];
            $variable3 = $r['column3'];
            $variable4 = $r['column4'];
            $variable5 = $r['column5'];
            $variable6 = $r['column6'];
            $variable7 = $r['column7'];

?>

//html code

<?php endwhile; } ?>




<?php function connectDB2 () {

    global $hostname, $db, $user, $pass;

    $dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

    $sql = "query 2";

    $query = $dbh->prepare($sql);
    $query->execute(array(//'placeholder',//'placeholder')); 
    $query->setFetchMode(PDO::FETCH_ASSOC); 

        while ($r = $query->fetch()): 

            $variable1 = $r['column1']; 
            $variable2 = $r['column2'];
            $variable3 = $r['column3'];
            $variable4 = $r['column4'];
            $variable5 = $r['column5'];
            $variable6 = $r['column6'];
            $variable7 = $r['column7'];

?>

//html code

<?php endwhile; } ?>

0 个答案:

没有答案