douyueju2912 2015-10-25 15:34
浏览 35
已采纳

我如何重新组织我的PHP代码以包含单独的数据库信息文件

Can any of you guys help me to reorganize this code? I'll try to explain the problem below.

I have a db_connection.php wich includes the following (just my db info and don't worry, i am just using it locally):

<?php
try {
    $db = new PDO('mysql:host=localhost;dbname=webappeind;charset=utf8','root','');
}
catch(PDOException $e) {
    echo $e->getMessage();
}
?>

But the problem is i have the following file that also includes my db info, but i do not know how to reorganize my code to get it working with my separate php file.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "webappeind";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    $sql = "SELECT * FROM zoekopdrachten ORDER BY titel DESC LIMIT 3";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output gegevens van elke rij
        while($row = $result->fetch_assoc()) {
            echo "<div class='recenttoegevoegd'>"."<a href='#'>".$row["titel"]."</a>"."</div>";
        }
    } else {
        echo "0 resultaten";
    }
?>
  • 写回答

1条回答 默认 最新

  • doulan4939 2015-10-25 15:56
    关注

    You can put the connection information in a separate file called, say, conn.php where you mention the code related to database opening, including credentials. Then, in the calling file, say putdata.php, you use the "require" or "require_once" command to include that conn.php. Let the conn.php file return a connection. Somewhat like this :

    <?php
    function GetMyConn() {
        $server_name = "localhost";
        $db_name = "db_name_goes_here";
        $db_user = "user_name_goes_here";
        $db_pass = "password_goes_here_muahhhaa";
        $db_full_addr = "mysql:host=" . $server_name . ";" . "dbname=" . $db_name;
    
        $MyConn = new PDO($db_full_addr, $db_user, $db_pass);
        $MyConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   
        return $MyConn;
    }
    ?>
    

    In the calling file, you would say, something like :

    require_once "GetConn.php";
    
    $MyConnHere = GetMyConn();
    $SqlHere = "Sql Statemetn goes here...."
    $SqlHere2 = $MyConnHere->prepare($SqlHere);
    $SqlHere2->execute();
    

    Also, I suggest you can download the source code of some open source PHP application, such as mantissa, and see how they have organized their code files, folders and settings.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题