HomeHowTo › Basic PHP & MySQL Usage Demo

Basic PHP & MySQL Usage Demo

This tutorial demonstrates the basic usage of PHP and MySQL. Everything is put together in the “index.php” file, except for the database connection which is outsourced to “db.php”. The code is fairly self-explanatory and contains the most commonly used commands (procedural style) for simple projects.

Update (2017-01-30): The code has been updated to be compliant with PHP7. The deprecated mysql commands like mysql_connect() or mysql_query() do no longer work. Instead, mysqli commands have to be used.

Content of db.php

1
2
3
4
5
6
7
8
<?php
$dbhost = "127.0.0.1";
$dbuser = "username";
$dbpass = "password";
$dbname = "tutorial";
$link = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) OR die("mysqli_connect failed");
mysqli_set_charset($link, "utf8") OR die("mysqli_set_charset failed");
?>

Note: Database connection variables should not be hardcoded into every file of the project because if you need to change anything you would have to touch all files. Therefore it’s better to outsource this code and include it if needed. For security reasons you should not use the database’s root account but an extra account that only has access to the necessary tables.

Content of index.php

Screenshot of the websitephp_mysql_usage_demo

Leave a Comment