php pdo close connection

PHP PDO connect and close connection in different functions

Maybe this is a silly question, but I am very new to PDO and am confused. Is it possible to instantiate a PDO object in one function (open a connection to a server/db) and then close the same connection in another function? Will the functions need to be passed the object to be able to close it? I want to do this so I can create a ubiquitous site-wide function that I can call to start a connection, execute non-generic sql, and then close it with another site-wide function. How can I do this? Do I need to pass the object to these function as arguments?

3 Answers 3

Yes, this is possible. I’d recommend using a constructor that initiates a connection to MySQL and a destructor that nullifies it. That way, you won’t have to manually call the function every time you want to open and close the connection. The connection will open whenever a new instance of the object is called, and when there are no further references to the object, the connection will be nullified.

It might look something like this:

You might find this reference about constructors and destructors useful: http://php.net/manual/en/language.oop5.decon.php

From my understanding you only have to connect to the database once and don’t have to open a connection for each function. The database connection will close automatically but you can close it manually by assigning the null value to the PDO object.

The connection is made when you instantiate the PDO object.

and closed automatically at the end of the script or when you assign it a null value

Источник

PDO PHP, как завершить соединение?

Но этот формат не работает. Соединение все равно открыто. Смотрю по Show process

php pdo close connection. Смотреть фото php pdo close connection. Смотреть картинку php pdo close connection. Картинка про php pdo close connection. Фото php pdo close connection

The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning NULL to the variable that holds the object. If you don’t do this explicitly, PHP will automatically close the connection when your script ends.

php pdo close connection. Смотреть фото php pdo close connection. Смотреть картинку php pdo close connection. Картинка про php pdo close connection. Фото php pdo close connection

php pdo close connection. Смотреть фото php pdo close connection. Смотреть картинку php pdo close connection. Картинка про php pdo close connection. Фото php pdo close connection

php pdo close connection. Смотреть фото php pdo close connection. Смотреть картинку php pdo close connection. Картинка про php pdo close connection. Фото php pdo close connection

php pdo close connection. Смотреть фото php pdo close connection. Смотреть картинку php pdo close connection. Картинка про php pdo close connection. Фото php pdo close connection

php pdo close connection. Смотреть фото php pdo close connection. Смотреть картинку php pdo close connection. Картинка про php pdo close connection. Фото php pdo close connection

php pdo close connection. Смотреть фото php pdo close connection. Смотреть картинку php pdo close connection. Картинка про php pdo close connection. Фото php pdo close connection

php pdo close connection. Смотреть фото php pdo close connection. Смотреть картинку php pdo close connection. Картинка про php pdo close connection. Фото php pdo close connection

Андрей: Последнее что пишет в логе mysql:

160704 9:17:38 InnoDB: Fatal error: cannot allocate memory for the buffer pool
160704 9:17:38 [ERROR] cannot allocate memory. Memory too low
160704 9:17:38 [ERROR] STATUS CRITICAL: mysqld
160704 9:17:38 [ERROR] Plugin ‘InnoDB’ init function returned error.
160704 9:17:38 [ERROR] Plugin ‘InnoDB’ registration as a STORAGE ENGINE failed.
160704 9:17:38 [ERROR] Unknown/unsupported storage engine: InnoDB
160704 9:17:38 [ERROR] Aborting

Через второй терминал и консоль, к сожалению не получается правильно посмотреть. Что первая, что вторая консоль на момент перегруза отваливается на секунд 10. То-есть топ замирает и прочее.

Источник

Connections and Connection management

Connections are established by creating instances of the PDO base class. It doesn’t matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).

Example #1 Connecting to MySQL

Example #2 Handling connection errors

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning null to the variable that holds the object. If you don’t do this explicitly, PHP will automatically close the connection when your script ends.

Note: If there are still other references to this PDO instance (such as from a PDOStatement instance, or from other variables referencing the same PDO instance), these have to be removed also (for instance, by assigning null to the variable that references the PDOStatement).

Example #3 Closing a connection

// and now we’re done; close it
$sth = null ;
$dbh = null ;
?>

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

Example #4 Persistent connections

If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.

If you’re using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it’s recommended that you don’t use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.

Источник

Is it necessary to close PDO connections

I noticed there is no close function for PDO. Should I close the connection or is it unnecessary for PDO?

php pdo close connection. Смотреть фото php pdo close connection. Смотреть картинку php pdo close connection. Картинка про php pdo close connection. Фото php pdo close connection

3 Answers 3

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning NULL to the variable that holds the object. If you don’t do this explicitly, PHP will automatically close the connection when your script ends.

So the answer is no, you don’t need to do anything unless you need to explicitly close the connection during the script execution for whatever reason, in which case just set your PDO object to null.

This question is depending a bit on the type of project and the type of connection.

In almost all of my projects I never manually close the connection. In PHP the connection (unless it is a persistent connection) will only be open during the request. So manually closing it is pretty useless anyway.

When looking at my projects where there was no persistent connection it would have been very hard to know when to manually close the connection either way. Once a project gets larger than a couple of files (and the individual components have no idea about eachother like they should) it becomes very hard to know when the connection will still be needed.

And opening the connection again when needed is waay more expensive than just leaving it open during the request.

Something though when working with persistent connection there will be situations where you will want to manually close the connection.

So to answer your question:

I noticed there is no close function for PDO.

You can nullify the object reference (and all references to the object) to manually close the connection in PHP.

Should I close the connection or is it unnecessary for PDO?

In most situations it is not necessary.

Источник

Connections and Connection management

Connections are established by creating instances of the PDO base class. It doesn’t matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).

Пример #1 Connecting to MySQL

If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().

Пример #2 Handling connection errors

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler().

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning NULL to the variable that holds the object. If you don’t do this explicitly, PHP will automatically close the connection when your script ends.

Пример #3 Closing a connection

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

Пример #4 Persistent connections

If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.

If you’re using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it’s recommended that you don’t use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.

Описание класса pdo, примеры использования класса pdo.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *