doudiza9154 2014-04-18 17:51
浏览 29
已采纳

使用PHP连接类到MySQL数据库,插入,更新,删除

I am about to start a new project, building a website in PHP using MySQL, javascript etc... My question is can i create a "connection class to MySQL database using PHP" once, and call that class every time I want to insert, update, or delete something. I'm new to php so go easy, can you send me example code, or link, to a tutorial. At the moment when I want to do a connection I put the connection at the top of the php which works but a lot of duplicated code on many pages.

category.php

<?php

    // connect to mysql db
    $con = mysqli_connect("localhost", "root", "");

    // use a mysql database
    mysqli_select_db($con, "gaa2013");

    // run a sqql query
    $result = mysqli_query($con, "select * from categories");

    print("<form method='POST' action=\"home.php?page=category\">");

        print("<select name = 'cat'>");
        print("<option selected=\"selected\" style=\"background-color: blue\">All</Option>");
            //print fields from each row
        while($row = mysqli_fetch_array($result)){
            $curr = $row['description'];
                print("<option value='$curr'>$curr</option>");

        }
        print("</select>");
            print("<input type=\"submit\" name=\"submit\" value=\"Select a Category\">");
        print("<hr>");

more code....

login.php

//If there are input validations, redirect back to the login form
if($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: index.php");
    exit();
}

// connect to mysql db
$con = mysqli_connect("localhost", "root", "");
// use a mysql database
mysqli_select_db($con, "gaa2013");
// run a sqql query
$result = mysqli_query($con,"select * from users WHERE username='$username'");
//$num_rows = mysql_num_rows($result);
    //Check whether the query was successful or not
if($result) {
    while($row = mysqli_fetch_array($result)){
        //echo "$num_rows Rows
";
        $id = $row['id'];
        $userp = $row['username'];
        $pass = $row['password'];
        $_SESSION['SESS_MEMBER_ID'] = $id;
        $_SESSION['SESS_USERNAME'] = $userp;
        $_SESSION['SESS_PASSWORD'] = $pass;
        session_write_close();
        header("location: home.php");
        exit();
    }
more code.....

thanks in advance

Gman

  • 写回答

1条回答 默认 最新

  • douqulv6059 2014-04-19 17:53
    关注

    Disclaimer: this is just an introduction. I do not advice this for regular use.

    Your target is to avoid this:

    // connect to mysql db
    $con = mysqli_connect("localhost", "root", "");
    
    // use a mysql database
    mysqli_select_db($con, "gaa2013");
    

    ... every time you want to make a connection.

    To do this, an approach it can be the Design Pattern: Singleton.

    Check its explanation out here.

    Now:

    class Database {
        private static $connection = null;
    
        public static function getInstance()
        {
            static $connection = null;
            if (null === $connection) {
                $connection = new Database();
            }
            return $connection;
        }
    
        /**
         * Protected constructor to prevent creating a new instance of the
         * *Singleton* via the `new` operator from outside of this class.
         */
        protected function __construct()
        {
            // connect to mysql db
            $con = mysqli_connect("localhost", "root", "");
    
            // use a mysql database
            mysqli_select_db($con, "gaa2013");
    
            return $con;
        }
    }
    

    Then, you would get and run database connections like this:

    // Get DB connection
    $connection = Database::getInstance();
    $result = mysqli_query($connection, "select * from categories");
    

    How that works?

    1. You request a new Database connection with Database::getInstance();
    2. Database::getInstance checks if it is null and, therefore, no connection has been requested yet. If so, constructs one. Otherwise, uses the already open connection.
    3. The database constructor is not available outside the Database object and therefore you can not request new Database(); from outside.

    I would like you to know, however, that nowadays it is discussed if the Singleton pattern is appropiate or not. I do not think that you should concern much about it, as long as you are learning. I recommmend you to play with these techniques yourself: test, try, see what happens, if you feel it is right or not.

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

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝