Create a new PHP page from your template and save it as sqlconnect.php. Put this line into the PHP section:
$dbconnection=mysqli_connect("localhost", "fred", "pass1234");
Save, upload and try and you should see an error something like this:
Warning: mysqli_connect(): (HY000/1045): Access denied for user 'fred'@'localhost' (using password: YES) in C:\web\beginnerssite\sqlconnect.php on line 28
SQL errors are often confusing but this one should make some sense. It is saying that you cannot access your server with that user name and password. You will fix that now.
To connect to a database server you will need a database server! XAMPP has one included (click Start next to SQL, MySQL or MariaDB) and pretty much any Web hosting company has one which should be running already. Any Linux server you set up will have one (the M in LAMP). The Web server, the PHP server and the database server will normally be running on the same computer. That makes it very easy for them to talk to each other but even if they are split up on different computers it will work the same way.
The parts of the line of code above are:
- before the equals sign is a variable to store the entrance or connection to the database server (any variable name would do but choose a sensible one like this one)
- after the equals is the function mysqli_connect() which will contact the database server and log in for you once it knows:
- the address of the database server (localhost just means the database server is on the same computer as the Web server which is handling the PHP)
- the user name you have on the database server
- the password for that user
Making it work
You will need to change the username and password to the ones set up on the server. On XAMPP that will be root and an empty password (delete the password from inside the "" but leave those quotes there). On a real server you will need to be told the user name and password. Generally localhost is correct unless your Web hosting company has told you different.
Save and try again and this time the page should be blank. You now have a connection to the database server and can send commands to it. Do not move on until you have got rid of the original error.