Reading a connection page, and its errors
The book’s connection page used an old family of database functions whose names begin with mysql, then an underscore (not the mysqli family). These were removed from PHP in version 7, and a page that calls them stops with an error. Today we use mysqli_connect, which takes the server, the user, the password and the database. The old logic was “if the connection worked, go on; else print not connected”. But in PHP 8.1 and later a failed mysqli_connect does not return false: it throws an exception, so an if and else would never reach the else. The right shape is try and catch. The risky call goes inside try; if it fails, catch runs. Read the page below: when a server is running, it prints connected; when none is running, it prints not connected. When something goes wrong, show the visitor a short, friendly message. Never print the server’s own error text or any detail of the connection: it can give secrets away.
1<?php 2try { 3 $connect = mysqli_connect("localhost", "dict_user", "a-long-secret", "dbdictionary"); 4 echo "connected"; 5} catch (mysqli_sql_exception $e) { 6 echo "not connected"; 7} 8?>
not connected
1<?php 2try { 3 $connect = mysqli_connect("localhost", "dict_user", "a-long-secret", "dbdictionary"); 4} catch (mysqli_sql_exception $e) { 5 echo "The dictionary is not available now. Please try again later."; 6} 7?>
The dictionary is not available now. Please try again later.
On paper, trace the page under “try and catch” when the password is wrong: which line runs first, what is thrown, which block runs, and what the visitor sees. Then write one friendly error sentence of your own for the visitor.