Do I need a php mysql connection in each function that uses database?

前端 未结 5 1138
无人共我
无人共我 2020-12-25 09:33

I am creating a php restful API and currently I have the database connection information in each function.

//Connect To Database
    $hostname=host;
    $use         


        
5条回答
  •  清歌不尽
    2020-12-25 09:59

    Why won't you move out the connection information into config and the call to mysql_connect into some factory?

    E.g.

    class ConnectionFactory {
        public static MysqlConnection CreateConnection() {
            $connection = mysql_connect(Config::$host, Config::$port etc);
            mysql_select_db($connection, Config::$schema);
            return $connection;
        }
    }
    

    and then in your code

    $connection = ConnectionFactory::CreateConnection();
    mysql_query($connection, $sqlApiAccess) or die('Error, insert query failed');
    

提交回复
热议问题