Current Location: Home> Latest Articles> How to Establish a Persistent Database Connection with mysql_connect Function? Step-by-Step Guide

How to Establish a Persistent Database Connection with mysql_connect Function? Step-by-Step Guide

gitbox 2025-09-11

In PHP, connecting to a MySQL database is a common task when developing web applications. There are several ways to establish a connection, and using the mysql_connect() function to create a persistent connection is a classic approach. This article provides a detailed explanation of how to use mysql_connect() for persistent connections, its working principle, and real-world applications.

What is a Persistent Connection?

A persistent connection means that once the connection is established, it will not close after the script finishes execution. Instead, it stays active and can be reused by the next script request. This reduces the overhead of repeatedly creating and closing connections, making it particularly useful for applications with frequent requests. In contrast, a regular connection is opened each time a script runs and then closed once execution completes.

Using mysql_connect to Create a Persistent Connection

In PHP, the mysql_connect() function can be used to establish a persistent connection. The basic syntax is as follows:

<span><span><span class="hljs-title function_ invoke__">mysql_connect</span></span><span>(</span><span><span class="hljs-string">&#039;hostname&#039;</span></span><span>, </span><span><span class="hljs-string">&#039;username&#039;</span></span><span>, </span><span><span class="hljs-string">&#039;password&#039;</span></span><span>, </span><span><span class="hljs-literal">true</span></span><span>);
</span></span>
  • 'hostname': The database server host address, usually localhost or an IP address.

  • 'username': The username used to connect to the database.

  • 'password': The password corresponding to the username.

  • The fourth parameter true indicates a persistent connection.

Difference Between Persistent and Regular Connections

  1. Connection Closing Mechanism:

    • Regular connection: Closed after each script finishes execution.

    • Persistent connection: Remains active even after the script ends, ready for reuse by subsequent requests.

  2. Performance Differences:

    • Persistent connections reduce the overhead of creating and destroying connections. They perform better in long-running or high-concurrency web applications.

    • Regular connections require creating a new connection for every request, which may cause bottlenecks under heavy load.

  3. Main Benefits of Persistent Connections:

    • Efficiency: Reduces repetitive connection setup.

    • Resource saving: Connections are reused within the pool for a certain period of time.

Steps to Implement Persistent Connections

Step 1: Ensure MySQL Configuration Supports Persistent Connections

First, confirm that MySQL configuration allows persistent connections. In the MySQL config file (my.cnf or my.ini), check the following settings:

<span><span><span class="hljs-section">[mysqld]</span></span><span>
skip-name-resolve
</span><span><span class="hljs-attr">wait_timeout</span></span><span> = </span><span><span class="hljs-number">28800</span></span><span>
</span><span><span class="hljs-attr">interactive_timeout</span></span><span> = </span><span><span class="hljs-number">28800</span></span><span>
</span></span>
  • skip-name-resolve: Disables DNS reverse lookups to avoid DNS queries for each connection.

  • wait_timeout and interactive_timeout: Define connection timeout values to prevent early disconnections.

Step 2: Use mysql_connect() to Establish a Persistent Connection

<span><span><span class="hljs-meta">&lt;?php</span></span><span>
</span><span><span class="hljs-comment">// Establish a persistent connection using mysql_connect</span></span><span>
</span><span><span class="hljs-variable">$link</span></span><span> = </span><span><span class="hljs-title function_ invoke__">mysql_connect</span></span><span>(</span><span><span class="hljs-string">&#039;localhost&#039;</span></span><span>, </span><span><span class="hljs-string">&#039;root&#039;</span></span><span>, </span><span><span class="hljs-string">&#039;password&#039;</span></span><span>, </span><span><span class="hljs-literal">true</span></span><span>);
<p></span>if (!$link) {<br>
</span>die(</span>'Could not connect: ' . mysql_error());<br>
}</p>
<p>echo 'Connected successfully!';<br>
// Other database operations...<br>
?><br>
</span>

Here, the fourth parameter of mysql_connect() is set to true, which requests a persistent connection. Once connected successfully, database operations can proceed.

Step 3: Perform Database Operations

Once the persistent connection is established, you can perform standard database operations, such as selecting a database and running queries:

<span><span><span class="hljs-title function_ invoke__">mysql_select_db</span></span><span>(</span><span><span class="hljs-string">&#039;my_database&#039;</span></span><span>, </span><span><span class="hljs-variable">$link</span></span><span>);
<p></span>// Execute SQL query<br>
$result = mysql_query('SELECT * FROM users', $link);</p>
<p>while (</span>$row = </span>mysql_fetch_assoc(</span>$result)) {<br>
</span>echo $row[</span>'username'] . '<br>';<br>
}<br>
</span>

Step 4: Closing the Connection (Optional)

For persistent connections, manual closing is not usually necessary because the connection remains active for reuse. However, if needed, you can explicitly close it with mysql_close():

<span><span><span class="hljs-title function_ invoke__">mysql_close</span></span><span>(</span><span><span class="hljs-variable">$link</span></span><span>);
</span></span>

Things to Watch Out for with Persistent Connections

  1. Connection Pool Limits:

    • Persistent connections may be limited by the maximum number of connections in MySQL. Excessive connections could exhaust the pool.

  2. Session State Issues:

    • Persistent connections preserve session state, such as previously set variables. If multiple scripts rely on different states, conflicts may occur.

  3. Resource Consumption:

    • While persistent connections improve performance, overuse without proper management can drain MySQL server resources.

  4. Security Concerns:

    • Since persistent connections last longer, ensure credentials (username, password) are secure to prevent misuse.

Conclusion

Using the mysql_connect() function for persistent connections helps reduce the overhead of frequent connection setup and teardown. This approach is especially useful for high-concurrency, database-intensive applications. However, careful resource management is essential to avoid session conflicts or overloading the connection pool. When configured and used properly, persistent connections can significantly enhance PHP database performance.