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 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了