John Davidson

php - Static Varible vs PDO::ATTR_PERSISTENT

0 comments
Message:


I have a database class that I developed. But I have doubts about performance in case of load. There are two issues that I was curious about and couldn't find the answer even though I searched.


When the database connection is bound to a static variable in the class,


class DB
{
static $connect;
......
function __construct()
{
try {
self::$connect = new PDO("{$this->db_database}:host={$this->db_host};dbname={$this->db_name};charset=utf8mb4", "{$this->db_username}", "{$this->db_password}");
self::$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$connect->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8mb4");
} catch ( PDOException $e ){
echo '<b>ERROR: </b>'.$e->getMessage();
exit;
}
}
}


PDO::ATTR_PERSISTENT => true

Does it have an equivalent ability?


Also, I didn't fully understand the pdo permalink logic, it uses the existing connection instead of opening a separate connection for each user. But how does he use the existing link here? For example "ip address" etc.


Thank you for your help.



My Answer:
"mysql:host=localhost;dbname=mydatabase", "username", "password");_ } catch (PDOException $e) {_ echo "Connection failed: " . $e->getMessage();_ }_ }_}_In this case, the database connection is stored in a static variable $connect. This means that the connection will be shared among all instances of the DB class. This can be beneficial in terms of performance as the connection will only be established once and reused for subsequent requests. However, it can also lead to potential issues with concurrency and thread safety._On the other hand, using PDO::ATTR_PERSISTENT flag when creating the PDO object can also improve performance by reusing the same connection for multiple requests. This flag tells PDO to use a persistent connection to the database, which can reduce the overhead of establishing a new connection for each request._In conclusion, both approaches have their pros and cons in terms of performance. It is important to consider the specific requirements of your application and test both approaches to see which one works best in your case.

Rate this post

3 of 5 based on 3854 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us