Connecting PHP to MySQL: mysql_connect() Migration

The historical mysql_connect() function opened a MySQL connection in PHP 4/5. That extension no longer exists in PHP 7 or PHP 8. Use PDO or MySQLi for current code.

Do not copy legacy code into a current project. The historical examples below are retained only so you can recognize and migrate old applications.

Historical mysql_connect() syntax

<?php
$link = mysql_connect($servername, $dbuser, $dbpassword);
?>

Old tutorials commonly followed it with mysql_select_db() and sometimes used mysql_pconnect() for persistent connections. Both belong to the removed extension.

<?php
// Historical only: removed from PHP 7+
$link = mysql_pconnect($servername, $dbuser, $dbpassword);
?>

Current connection with PDO

<?php
$dsn = 'mysql:host=localhost;dbname=sql_tutorial;charset=utf8mb4';
$dbo = new PDO($dsn, 'userid', 'password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
?>

The database name and charset are part of the DSN, so a separate mysql_select_db()-style call is unnecessary.

Current connection with MySQLi

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli('localhost', 'userid', 'password', 'sql_tutorial');
$connection->set_charset('utf8mb4');
?>

See the dedicated PDO connection and MySQLi connection tutorials for application setup.

Persistent connections

The old mysql_pconnect() behavior should not simply be copied into a modern application. Persistent connections have different lifecycle and deployment implications. Start with normal PDO/MySQLi connections unless you have a measured reason to use persistence.

Next: closing or releasing a MySQL connection.

← All PHP & MySQL topics




Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer