• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Nikkster's PHP Lesson Part 2, variables, operators & MySQL

Nikkster

Programmer
Joined
May 9, 2008
Messages
2,848
Reaction score
9
Location
Confidential
Hi and welcome back to my PHP & MySQL tutorial. In this chapter/lesson, I will teach you some about variables, operators & how to connect to MySQL and how to communicate it with PHP.

Please make sure you read this also: http://otland.net/f481/nikksters-php-lesson-part-1-intro-basics-99811/

TL;DR :)

Anyway, so let's start.

VARIABLES
What is a variable?
variable is a symbolic name given to some known or unknown quantity or value, for the purpose of allowing the name to be used independently of the value it represents. A variable name in computer source code is associated with a data storage location --and thus its contents, which generally change during the course of program execution. - Wikipedia

Why use variables?
Using variables in your PHP codes can save you a lot of time, let me show you. Let's say, you have a volvo and the color of the car is yellow. Now you are going to announce something on a website, teling that you would like to purchase a car or sell a car. But now you are too lazy to write volo and yellow over and over again, so we will do it with PHP.

PHP:
<?php
$mycar = 'volvo';
$color = 'yellow';

echo "I am selling a $mycar and it is $color"; 
?>
This will print "I am selling a volvo and it is yellow" on the website. So basically, what we are doing here is, we declare volvo and yellow into two variables and tells the PHP that we use $mycar and $color in our code and that it should print that on the page, with "echo".

OPERATORS
Do you remember your math? Yes? Good, because we are going to create a basic PHP program that's going to calculate terms and give us the sum of it.

Let's say, you have a simple HTML form on your website and a visitor wants to know what 5+5 is or 5-5 is or 5/5 is, etc. - Then you will need a program that calculates that for you and echo whether the result of is correct or wrong, on the website. But I don't want to go too far yet, so we will pop the breakes a little. However, let's start by writing our program.

PHP:
<?php
$num1 = '5'; // Number 5 
$num2 = '5'; // Number 5 
$sum = ($num1+$num2); // 5+5 (variable + variable)

if($sum == 10) { // If the result is 10, then print "Correct"
echo "Correct!";
} else {
echo "Wrong, you really don't know what 5+5 is??!"; // If not 10, then print "Wrong, you really don't know what 5+5 is??!
}
?>
We are going to talk more about if-statements in our next tutorial, so don't care about it yet, if you don't want to.

MySQL
What is MySQL?
MySQL is a relational database management system (RDBMS)[1] that runs as a server providing multi-user access to a number of databases. - Wikipedia

Why saving information in a database instead of in a .txt file?
Because of the security.

ESTABLISHING A MYSQL CONNECTION
Now we are going to establish a MySQL connection, in order to be able to communicate with our database.

PHP:
<?php
$dbhost = 'localhost'; // The name of the host, usually 127.0.0.1 or localhost
$dbuser = 'root'; // The username of the database, usually set as "root" as default
$dbpass = 'password'; // The password to the database
$db = 'database'; // And finally, the database that we are going to store information in. 

// We use mysql_connect to tell PHP that we want to establish a connection to our database and filllin the information, and as well as database

mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()); 
mysql_select_db($db) or die(mysql_error());

// or we can do this

mysql_connect("localhost","root","password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
?>
Let's put this in a file called "config.php".
Any questions so far? Post in this thread.

CREATING TABLES IN OUR DATABASE​
First before we can communicate with the database, we will need to create a database and setup tables. If you don't know how to do this, ask in this thread or find other tutorials in this forum section.

Let's say, you are going to create a member system. You want your users to have a username, password & email. The SQL code should look like this:
PHP:
CREATE TABLE users ( 
`id` smallint(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(40) NOT NULL,
`password` VARCHAR(40) NOT NULL,
`email` VARCHAR(40) NOT NULL,
PRIMARY KEY (id));
What we are doing here is, we create one column called "id" which should be automated. This will make it a lot easier for us in the future to choose a specific user. To do this, we use smallint(11) and AUTO_INCREMENT and then we need to inform MySQL that our primary key is (id) and this is obligated.

MySQL INSERT​
Why do we use MySQL insert?
If we want to insert information to our database, we need to use "INSERT". Now we have created a database called "users" and a table called "users".

Our code should look like this:
PHP:
mysql_query("INSERT INTO `users` (username, password, email) VALUES('$username','$password','$email')"); // This will be more obvious as soon as I have explained how to use the $_POST and HTML forms.

And we're done for this lesson. I will see you in my next tutorial which should be up soon, also. :)

Good luck!
 
Last edited:
Dont teach people to use mysql_* functions, its better to depend on MySQLi class.
PHP:
$sql = new MySQLi(host, user, password, db);

Also, if you know that $num1 and $num2 are integers, why do you use quotation marks on them?
PHP:
$num1 = 5;
$num2 = 5;
//
list($num1, $num2) = array(5, 5);

In your example it would be better to tell php that it is an integer by:
PHP:
$num1 = '5'; // Number 5 
$num2 = '5'; // Number 5 
$sum = ((int)$num1+(int)$num2); // 5+5 (variable + variable)

Also, I dont think your INSERT INTO will work.
PHP:
$sql->query("INSERT INTO `users` (`username`, `password`) VALUES('{$username}', '{$password}');");
 
Last edited:
Dont teach people to use mysql_* functions, its better to depend on MySQLi class.




Also, I dont think your INSERT INTO will work.
PHP:
$sql->query("INSERT INTO `users` (`username`, `password`) VALUES('{$username}', '{$password}');");

No, this would work:
PHP:
mysql_query("INSERT INTO `users` (username, password, email) VALUES('$username','$password','$email')");

And yes, I can teach them how to use MySQLi, but this was about MySQL.

I am sorry for any confusion. I wrote this early in the morning, however, I will change the last line immediately.
 
Awesome!
Can you make a tutorial on how to let people input something, like make an acc? To create an account etc :D
 
Someone told me to teach MySQLi instead, so I will write a few lines here.

To setup a connection, do this:
PHP:
// connection
$connect = new MySQLI('localhost','root','password','database') or die(mysql_error()); 

// Get something from the database
$id = $_GET['id']; 
$fetch = $connect->prepare("SELECT username, password FROM users WHERE `id` = '$id'"); 
while($row = $fetch->fetch()) : 
$username = strrpos($excerpt, '...');

This is a little more advanced. Your choice, MySQL or this.

or OOP:

PHP:
class MySQLDB 
{
function dbConnect() {
$connect = new MySQLi('localhost','root','password','database') or die('Could not establish a connection');
   }
 }
 
Last edited:
or OOP:

PHP:
class MySQLDB 
{
function dbConnect() {
$connect = new MySQLi('localhost','root','password','database') or die('Could not establish a connection');
   }
 }
MySQLi is Object Oriented Programming already, no need for an external class. Unless you wish to extend the MySQLi library/adapt it to a database using special methods.
 
PHP:
mysql_query("INSERT INTO `users` (username, password, email) VALUES('".$username."','".$password."','".$email."')");

is the properly concatinated non-shortcut way of doing the mysql code.
 
Back
Top