简体   繁体   English

连接数据库

[英]Connection to database

I am having trouble configuring my connection. 我在配置连接时遇到问题。 I have a getConnection method that looks like this: protected function getConnection(){ 我有一个如下所示的getConnection方法:受保护的函数getConnection(){

$mysqli = new mysqli('xxxxxxxxx', 'xxxxxx', 'xxxxxx', 'xxxxxxx');

if($mysqli->connect_errno > 0){
    die('Unable to connect to database [' . $mysqli->connect_error . ']');
   }
 }

within every test function I am forced to implement the following code to get connection to the database: $mysqli = new mysqli('xxxxxxxxxx', 'xxxxxxxxx', 'xxxxxx', 'xxxxxxx'); 在每个测试函数中,我都必须执行以下代码以获取与数据库的连接: $mysqli = new mysqli('xxxxxxxxxx', 'xxxxxxxxx', 'xxxxxx', 'xxxxxxx');

how do I call the getConnection() method in a more correct manner? 如何以更正确的方式调用getConnection()方法? I have tried things such as: $mysqli=parent::getConnection(); 我已经尝试过诸如: $mysqli=parent::getConnection(); but I always get error messages stating that the method is undefined. 但我总是收到错误消息,指出该方法未定义。 Any thoughts? 有什么想法吗?

If your connection is shared between several functions, and that's usually the case since you want to connect to your database only once by page call and not once by function call , then create your mysqli object in a persistant scope, not in a function scope. 如果您的连接在多个函数之间共享,并且通常是这种情况,因为您只想通过页面调用 一次而不是通过函数调用 一次连接到数据库,那么请在持久作用域而不是函数作用域中创建mysqli对象。

Then you access it as a function parameter, a [parent] class attribute or a global variable depending on your code. 然后根据您的代码将其作为函数参数,[父]类属性或全局变量进行访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM