Search Our Database
Example of PHP mysql_connect
Introduction:
This guide demonstrates how to establish a connection to a MySQL database using PHP’s mysql_connect() function. It is aimed at web developers and system administrators working with PHP and MySQL to create dynamic web applications. By following this example, you’ll gain an understanding of the basic steps required to connect a PHP script to a MySQL database. The information here applies when you are working with legacy PHP code, as the mysql_connect() function is deprecated in more recent PHP versions. It is useful when you need to maintain or troubleshoot older applications still using this function. The example provided will help explain each part of the code so you can adapt it for your own database connections.
<!--?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); ?-->
Breakdown:
- mysql_connect(‘localhost’, ‘mysql_user’, ‘mysql_password’):
- Establishes a connection to the MySQL database using the provided host (localhost),username (mysql_user),and password (mysql_password).
- Returns: A resource link identifier representing the connection on success, or false on failure.
- if (!$link) { die(‘Could not connect: ‘ . mysql_error()); }:
- Checks if the connection failed by testing whether $link is false.
- If the connection failed, it calls die(), which terminates the script and outputs the error message “Could not connect” along with the specific error using mysql_error().
- echo ‘Connected successfully’; :
- If the connection is successful, it prints a success message.
- mysql_close($link);:
- Closes the connection to the MySQL database to free up resources. $link is the resource link identifier from the earlier connection.
Why Deprecated:
- The mysql extension was removed in PHP 7.0. It doesn’t support modern MySQL features (like prepared statements) and is not secure against SQL injection.
Conclusion:
While the script demonstrates how to connect to a MySQL database using the old mysql extension, it’s important to update any code that uses this method. Modern alternatives like mysqli or PDO are more secure, reliable, and support advanced features, making them the best choice for current PHP development.