简体   繁体   中英

How do i setup persistent connections in php

i do have a website which just write and read some data from my database. for this purpose, i decided to use prepared statements but i have no clue how i can setup this stuff once, without creating them on every call like the database connection.

lets say, you call website.com/write.php. write.php then "require" "settings.php" to get the database connection. This causes the connection to be initialized (as the prepared statements too) every time you call something on my website.

How do i pretend this behaviour?

you can use static classes for to achieve that. You can create a class Database, in a file named Database.php for example. Then in that class you create a static property, for example $connection and a function to load that property if it's empty. Then in your file settings.php you just import that class and use the same connection everywhere by just calling Database::connection->function(..) .

However, it's not always a good practice. Maybe you don't even need persistent connection, but auto-initialization of the database connection based on some dynamic settings per user. You can store these settings in sessions and recreate connection with these settings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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