In PHP 8, the mysql extension has been removed and is no longer supported. Instead, the mysqli (improved MySQL) extension and PDO (PHP Data Objects) extension should be used to handle MySQL connections. Here are examples of how to create functions for each extension:
Using mysqli extension:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function connect_mysqli() { $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } return $conn; } |
This function creates a connection to the MySQL database using the mysqli extension, and returns the connection object. It takes no parameters, and assumes that the server, username, password, and database name are hardcoded within the function. You can modify it to accept parameters for these values if needed.
Using PDO extension:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function connect_pdo() { $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } catch(PDOException $e) { die("Connection failed: " . $e->getMessage()); } } |
This function creates a connection to the MySQL database using the PDO extension, and returns the connection object. It takes no parameters, and assumes that the server, username, password, and database name are hardcoded within the function. You can modify it to accept parameters for these values if needed.
Note that in both cases, the function checks for connection errors and will terminate the script with an error message if there is a problem connecting to the database. It’s also a good practice to close the connection after you’re done using it, either by explicitly calling $conn->close() for mysqli or $conn = null for PDO.