<?php
// This part is unrelated to the article body, only serves as a preface example
echo "Hello, this is a PHP article generator!";
?>
When working with PHP and MySQL databases, developers often need to frequently establish and close database connections. For high-traffic sites, this process not only increases the server load but also impacts overall performance. To solve this issue, PHP provides the mysql_pconnect() function.
<?php
// Connect to the database using a persistent connection
$link = mysql_pconnect("localhost", "root", "password");
<p>if (!$link) {<br>
die("Connection failed: " . mysql_error());<br>
} else {<br>
echo "Persistent connection established successfully!";<br>
}</p>
<p>// Select a database<br>
mysql_select_db("test_db", $link);</p>
<p>// Execute a query<br>
$result = mysql_query("SELECT * FROM users");</p>
<p>while ($row = mysql_fetch_assoc($result)) {<br>
echo $row['username'] . "<br>";<br>
}<br>
?><br>
Since mysql_pconnect() is deprecated, it is better to use the mysqli extension’s mysqli_connect() with the p: prefix for persistent connections, or enable PDO::ATTR_PERSISTENT with PDO. These approaches not only ensure compatibility with newer versions of PHP but also provide richer features and improved security.
Summary: While mysql_pconnect() can improve database performance in some scenarios, its deprecation and resource management issues make it more practical to use mysqli or PDO for persistent connections in real-world projects.