[PHP] Variables in PHP

Bryon

I Fix Things
Messages
8,149
Reaction score
101
Points
48
Variables In PHP

What are variables: Variables are "little" pieces of information that can store pretty much any data in them. From integers to strings to arrays, Variables can hold them.

Introduction: In almost all PHP scripts, you will need to store, move, and manipulate data. You can do this by using variables. This tutorial is going to be aimed at teaching you how to use variables in PHP.

To start:

Variable types:

The two main data types that PHP variables use that a "beginner" should be worried with are integers and strings. There are many more data types of variables, just beginners don't need to worry about them until they "advance" in their knowledge of PHP. Some of the other data types that PHP can hold in vairables are:

- Arrays
- Boolean
- Objects
- Doubles


Rules When Creating Variables:

Variables in PHP can be named whatever you would like. But, there are some basic "rules" to go by:

- Variables start with a "$", always.
- Variables must begin with a letter, "[a-Z]", or underscore, "_".
- When placing data into variables, you must "encase" the data, if it is a string of mixed chars with "quotes", or 'apostrophes' . Example:

Code:
$hmhm = "some chars in here... 1321231";
$hmhm = 'some chars in here... 1321231';
If your data is only numbers, you do not need the quotes or apostrophes. Example:

Code:
	 $hmhm = 54654;

- Variable names are CaSe-SeNsItIvE, meaning that, if you have the variable "$hello", and the variable "$Hello", they are not the same variable. Yet, two completely seperate ones.
- Variables in PHP are "loose", meaning that they can change "on-the-fly" anywhere in your script. That also means that the "type" of the variable can be changed also. An example would be:

Say you have the variable $heyhey. Now:

Code:
 $heyhey = 1234;

Since PHP is "loose" when dealing with variables, you can then do something like:

Code:
 $heyhey = "Haha";

Somewhere later in your script, which would change teh value of $heyhey to "Haha", instead of "1234". You will see how this can be to your benifit later on.

What can be done with variables:

You can do many things with variables. They can be used in mathmatical equations, functions, mysql querys, and pretty much anything else you could think of. Here is an example of what could be done:

Code:
 $name = $_POST['name']; 
 
if (!$name) {
 
		 echo "No name was entered.";
 
} else {
 
		 $name = ucfirst($name);
		 echo $name ." is the name you have entered.";
 
}

Know, you might not understand what that does, but it uses variables to do "it". It takes the $_POST array, with the "name" form submit entered, or $_POST['name'], and places it into the variable $name. The script does some simple checking and formatting of $name, then either echos it, if it exists, or echos that no name was entered if it doesnt.

Anyways, to move on.

Manipulating variables:

You can do most "arithmatic" operations to variables. Including, but not limited to:

+ Addition
- Subtraction
/ Division
* Multiplication
% Modulus

I'm not goign to go into depth and describe what those all do, as you should be able to figure that out.

You can perform any of these on variables. Example:

Code:
$a = 5;
$b = 15;
$c = $a + $b; 
echo $c;		 // would output 20

......

Code:
$a = 5;
$b = 15;
$c = $b - $a; 
echo $c;		 // would output 10

......

Code:
$a = 5;
$b = 15;
$c = $b/$a; 
echo $c;		 // would output 3

Get what I mean?

Also, you can join two or more variables, using the "concatenate" operator. All that this is, is a "period" placed between 2 or more variables. Example:

Code:
$a = "Hello ";
$b = "World!";
$c = $a . $b;
echo $c;		 // Would output "Hello World!"


There are many more operators that can be used with PHP variables, including comparison, logical, incremental/decremental, and combined operators. I will discuss them in a later tutorial.

Once you become more knowledgeable in PHP, you might come across a situation where you need to do many mathmatical "operations" and put the result into a variable. Just like in math, (geometry, etc), order of operations "occurs". So if you have:

Code:
$a = 4 + 6 / 2;
echo $a;

That would echo 7, instead of 5.

You can use "paentheses ( and )" though, to change which operations you want first. An example would be:

Code:
$a = ((5 + 7) - 2) * 2;
echo $a;

That would echo 20.


Conclusion:

I think that just about covers basic variables in PHP. There are many, many more things that I have skipped over, that maybe I will write more tutorials on in the future.

Some of the things I have skipped are:

- comparison, logical, incremental/decremental, and combined operators.
- Arrays
- Logical statements
- Boolean variables
- Variables being "true", "false"


Like I said, I hope to talk abotu all of those in later tutorials.

One last thing. If you ever want to get rid of a variable, completly, you can use PHP's built-in function "unset()". Unset() completly "erases" a variable from memory, so it does not exist anymore, until created again. Example:

Code:
 $a = "Hmm"; 
echo $a;				 // would output "Hmm"
unset($a);
echo $a				 // Wouldn't output anything.
I hope this is a help to people starting out in PHP.

If I have forgotten ANYTHING at all in here, or you feel anything should be added into this, please tell me ASAP. This was written by ME, NedreN, and should not appear on any other websites without my permission. Unless I place it on there. Right now, the only site this is going on is x10Hosting's.

I'll prolly edit this a few times to fix mistakes.
 
Last edited:

o0slowpaul0o

New Member
Messages
254
Reaction score
0
Points
0
Nice tutorial..=)

Most veribals some times can be created by lang files or like IPB class_display.php what made IPB script url to make it short. But very good tutorial.
 

Bobswat

New Member
Messages
104
Reaction score
0
Points
0
haha, NEDREN's TUTORIAL IS AWESOME!!!!!
thank you nedren, it helped me
 

mirclin

New Member
Messages
1
Reaction score
0
Points
0
I am joining the ranks of novice PHP programmers; I hope that everything I have learned about javascript, VBscript, and VB can be of use in my projects.

I think that once I completely understand the _POST[] array that I will have an easier time working with the data input.

Oh and thanks for the quick information to get me started :)
 
Last edited:

Zepheria

New Member
Messages
15
Reaction score
0
Points
0
Very nice tut. Mirclin, the _POST array is very powerful when you know how to use it.
 

Brandon

Former Senior Account Rep
Community Support
Messages
19,181
Reaction score
28
Points
48
If you want to see how the $_POST works nice, make a form, post it and put this in the post to page.

Code:
print_r($_POST);

It'll help out alot:).
 

sm3xy

New Member
Messages
2
Reaction score
0
Points
0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Server Status Page</title>
</head>
<body>
<center>
<b>Server Status</b><br />
<img src="rslogo.png" alt="logo" /><br /><br />
<?php
if ($_GET['id'] == "register") {
echo "<form action=\"?id=submit\" method=\"post\">You can only add online servers to this list.<br /><br />Server Name:<br /><input type=\"text\" name=\"name\" /><br />Server IP:<br /><input type=\"text\" name=\"ip\" /><br />Port:<br /><input type=\"text\" name=\"port\" /><br /><br /><input type=\"submit\" value=\"Submit\" /></form><p><br />Click <a href=\"Server_Status.php\">here</a> to go to the main page.<br /></p>";
} else if($_GET['id'] == "submit") {
$Server_Name = $_POST['name'];
$Server_IP = $_POST['ip'];
$Server_Port = $_POST['port'];
if (($Server_Name != NULL) && ($Server_IP != NULL) && ($Server_Port != NULL)) {
$checkReg = @fsockopen("$Server_IP", "$Server_Port", $errno, $errstr, 1);
if($checkReg) {
$con = mysql_connect("localhost", "Username", "Password") or die(mysql_error());
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Database") or die(mysql_error());
mysql_query("INSERT INTO `serverstatus` (`Name`, `IP`, `Port`, `Uptime`, `Total`) VALUES ('$Server_Name', '$Server_IP', '$Server_Port', '1', '1')");
mysql_close($con);
echo "<br />Your Server has been successfully added to the list!";
} else {
echo "Invalid information or the server is down.<br />";
}
} else {
echo "You did not fill in all of the required information!";
}
echo "<p><br />Click <a href=\"Server_Status.php?id=register\">here</a> to add your own server or <a href=\"Server_Status.php\">here</a> to check the list.<br /></p>";
} else {
echo "<table><tr><td class=\"header\"><u>Server Name</u></td><td class=\"header\"><u>Server Status</u></td><td class=\"header\"><u>IP Address</u></td><td class=\"header\"><u>Port</u></td><td class=\"header\"><u>Uptime</u></td></tr>";
$Host = "localhost";
$User = "Username";
$Password = "Password";
$DBName = "Database";
$Link = mysql_connect ($Host, $User, $Password);
$Query = "SELECT * from `serverstatus`";
$Result = mysql_db_query ($DBName, $Query, $Link);
if ($Result) {
while ($Row = mysql_fetch_array ($Result)) {
@mysql_connect($Host, $User, $Password) or die(mysql_error());
@mysql_select_db ($DBName) or die(mysql_error());
$checkCurr = @fsockopen("$Row[IP]", "$Row[Port]", $errno, $errstr, 1);
$total = $Row[Total] + 1;
echo "<tr><td class=\"lista\">";
echo "$Row[Name]";
echo "</td><td class=\"lista\">";
if($checkCurr) {
$uptime = $Row[Uptime] + 1;
echo "<img src=\"online.gif\" alt=\"online\" />";
$UpdateDB = mysql_query("UPDATE `serverstatus` SET Uptime = $uptime WHERE Uptime = $Row[Uptime]");
} else {
echo "<img src=\"offline.gif\" alt=\"offline\" />";
}
$UpdateDB2 = mysql_query("UPDATE `serverstatus` SET Total = $total WHERE Total = $Row[Total]");
echo "</td><td class=\"lista\">";
echo "$Row[IP]";
echo "</td><td class=\"lista\">";
echo "$Row[Port]";
echo "</td><td class=\"lista\">";
$accuracy = $uptime/$total;
if ($accuracy == 1) {
$accuracy = $accuracy * 100;
} else {
$accuracy = 100 - $uptime/$total;
}
echo "$accuracy%";
echo "</td></tr>";
}
} else {
$create = 'CREATE TABLE `serverstatus` (
`Name` VARCHAR (20) NOT NULL,
`IP` VARCHAR (50) NOT NULL,
`Port` VARCHAR (6) NOT NULL,
`Uptime` VARCHAR (999999) NOT NULL,
`Total` VARCHAR (999999) NOT NULL,
PRIMARY KEY (`Name`)
)';
mysql_query($create);
mysql_close();
}
echo "</table><p><br />Click <a href=\"Server_Status.php?id=register\">here</a> to add your own server to the above list.<br /></p>";
}
?>
</center>
<center>
<p><a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></p>
</center>
</body>
</html>

It might be long why dont it work on my site?? :(
 

Slothie

New Member
Messages
1,429
Reaction score
0
Points
0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Server Status Page</title>
</head>
<body>
<center>
<b>Server Status</b><br />
<img src="rslogo.png" alt="logo" /><br /><br />
<?php
if ($_GET['id'] == "register") {
echo "<form action=\"?id=submit\" method=\"post\">You can only add online servers to this list.<br /><br />Server Name:<br /><input type=\"text\" name=\"name\" /><br />Server IP:<br /><input type=\"text\" name=\"ip\" /><br />Port:<br /><input type=\"text\" name=\"port\" /><br /><br /><input type=\"submit\" value=\"Submit\" /></form><p><br />Click <a href=\"Server_Status.php\">here</a> to go to the main page.<br /></p>";
} else if($_GET['id'] == "submit") {
$Server_Name = $_POST['name'];
$Server_IP = $_POST['ip'];
$Server_Port = $_POST['port'];
if (($Server_Name != NULL) && ($Server_IP != NULL) && ($Server_Port != NULL)) {
$checkReg = @fsockopen("$Server_IP", "$Server_Port", $errno, $errstr, 1);
if($checkReg) {
$con = mysql_connect("localhost", "Username", "Password") or die(mysql_error());
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Database") or die(mysql_error());
mysql_query("INSERT INTO `serverstatus` (`Name`, `IP`, `Port`, `Uptime`, `Total`) VALUES ('$Server_Name', '$Server_IP', '$Server_Port', '1', '1')");
mysql_close($con);
echo "<br />Your Server has been successfully added to the list!";
} else {
echo "Invalid information or the server is down.<br />";
}
} else {
echo "You did not fill in all of the required information!";
}
echo "<p><br />Click <a href=\"Server_Status.php?id=register\">here</a> to add your own server or <a href=\"Server_Status.php\">here</a> to check the list.<br /></p>";
} else {
echo "<table><tr><td class=\"header\"><u>Server Name</u></td><td class=\"header\"><u>Server Status</u></td><td class=\"header\"><u>IP Address</u></td><td class=\"header\"><u>Port</u></td><td class=\"header\"><u>Uptime</u></td></tr>";
$Host = "localhost";
$User = "Username";
$Password = "Password";
$DBName = "Database";
$Link = mysql_connect ($Host, $User, $Password);
$Query = "SELECT * from `serverstatus`";
$Result = mysql_db_query ($DBName, $Query, $Link);
if ($Result) {
while ($Row = mysql_fetch_array ($Result)) {
@mysql_connect($Host, $User, $Password) or die(mysql_error());
@mysql_select_db ($DBName) or die(mysql_error());
$checkCurr = @fsockopen("$Row[IP]", "$Row[Port]", $errno, $errstr, 1);
$total = $Row[Total] + 1;
echo "<tr><td class=\"lista\">";
echo "$Row[Name]";
echo "</td><td class=\"lista\">";
if($checkCurr) {
$uptime = $Row[Uptime] + 1;
echo "<img src=\"online.gif\" alt=\"online\" />";
$UpdateDB = mysql_query("UPDATE `serverstatus` SET Uptime = $uptime WHERE Uptime = $Row[Uptime]");
} else {
echo "<img src=\"offline.gif\" alt=\"offline\" />";
}
$UpdateDB2 = mysql_query("UPDATE `serverstatus` SET Total = $total WHERE Total = $Row[Total]");
echo "</td><td class=\"lista\">";
echo "$Row[IP]";
echo "</td><td class=\"lista\">";
echo "$Row[Port]";
echo "</td><td class=\"lista\">";
$accuracy = $uptime/$total;
if ($accuracy == 1) {
$accuracy = $accuracy * 100;
} else {
$accuracy = 100 - $uptime/$total;
}
echo "$accuracy%";
echo "</td></tr>";
}
} else {
$create = 'CREATE TABLE `serverstatus` (
`Name` VARCHAR (20) NOT NULL,
`IP` VARCHAR (50) NOT NULL,
`Port` VARCHAR (6) NOT NULL,
`Uptime` VARCHAR (999999) NOT NULL,
`Total` VARCHAR (999999) NOT NULL,
PRIMARY KEY (`Name`)
&nbsp;)';
mysql_query($create);
mysql_close();
}
echo "</table><p><br />Click <a href=\"Server_Status.php?id=register\">here</a> to add your own server to the above list.<br /></p>";
}
?>
</center>
<center>
<p><a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></p>
</center>
</body>
</html>

It might be long why dont it work on my site?? :(


Are you not posting in the wrong section?
 

supajason

Member
Messages
288
Reaction score
2
Points
18
I see one thing at first look:

Code:
$User = "Username";
$Password = "Password";
$DBName = "Database";

you need to fill out your username, password and database to connect to SQL server.
 
Last edited:
Top