Open your PHP template. At the top of the code but under the error report lines add a new blank line. Paste this in:
$dbconnection=mysqli_connect("localhost", "root", "") or die("Error connecting to database: ".mysqli_error($dbconnection)); mysqli_select_db($dbconnection, "ywstutorial") or die("Error selecting database: ".mysqli_error($dbconnection));
Now at the very bottom of the code make a new line (below </html>) and paste this in:
<?php mysqli_close($dbconnection) or die("Error closing connection: ".mysqli_error($dbconnection)); ?>
You should now have five lines of PHP code at the top of every PHP page which turn error reporting on and connect to your database server. Then at the end the connection is closed. If you do not need SQL on any new PHP pages you can delete those three lines. You may also need to change the ywstutorial database name for different pages.
You have presumably made a coding mistake or two so far. When you do you will sometimes get an error message but sometimes not. On a hosted server you should never see error messages as that is considered a security risk.
The new code above (on the end of all of the SQL-related lines) is asking PHP:
- to try to do the first bit (the original code)
- or if that doesn't work show the user the SQL error message instead and then stop executing the page
The die() function stops the PHP from executing any more and gives you an error message. Here the messages are partly the text you choose (e.g. Error closing connection:) and partly an error sent from the SQL server and obtained using the PHP function mysqli_error(). Some of those errors are confusing but it may help.
You will see them in action very soon which should make them easier to understand.