If you are interested in building web applications and working with databases but do not know where to start you have come to the right place. In our previous articles we have covered topics likePHP and MySQL setup for Windows and Linux OS. Today we will dive into the basics of PHP. As a powerful and versatile programming language, PHP is widely used for developing dynamic web applications, handling files and connecting to databases.By mastering its fundamentals you can take your web development skills to the next level.
In this guide we will focus specifically on the basics of PHP web development and database connectivity. From variables and data types to operators, control structures and functions we will cover everything you need to know to get started with PHP.With real world examples and best practices we will guide you through the process of connecting PHP to a database and working with common database operations like reading, writing and updating data.
Whether you are a beginner or have some experience with other programming languages this guide will provide a solid foundation for building your skills in PHP and developing your own web applications.So let's Get started and learn the basics of web development and database connectivity in PHP to become a proficient web developer .
Here are some of the basics of PHP:
- Syntax: PHP code is typically embedded within HTML, using opening and closing tags respectively. PHP statements end with a semicolon (;).
- Variables: In PHP you can define variables using the $ symbol, followed by the variable name. For example, $name = "John"; assigns the value "John" to the variable $name.
- Data Types: PHP has various data types, including strings, integers, floats, booleans, arrays and objects.
- Operators: PHP has various operators including arithmetic (+, -, *, /, %), assignment (=), comparison (==, !=, >, <, >=, <=), and logical (&&, ||, !).
- Control Structures: PHP has various control structures, including if-else statements, switch statements, while and do-while loops ,for loops and foreach loops.
- Functions: PHP allows you to define and call functions. Functions are used to perform specific tasks and can be reused throughout your code.
- Forms: PHP is commonly used in web development to process data submitted through HTML forms.
1.Syntax:
PHP is a server side scripting language which means that the code is executed on the server before the resulting HTML is sent to the client's browser. PHP code is typically embedded within HTML using opening and closing tags respectively.Here is an example of PHP code that prints "Hello world!" to the screen:
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello world!";
?>
</body>
</html>
In Example echo statement is used to print the text "Hello world !" to the screen.
get started with running PHP code on your PC the first step is to run XAMPP controller .This will allow you to run PHP code on your computer/PC. Once XAMPP is running navigate to the C > xampp > htdocs folder on your PC. In this folder create a new folder called "test".Next create a new file in this folder called "index.php". You can open this file in a plain text editor like notepad or you can download a more advanced editor like Sublime & Visual Studio .
After opening the "index.php" file in your text editor copy the PHP code from above and paste it into the file. Save the file close the editor. You re now ready to run your first PHP Code .
To do this open your web browser (such as Google Chrome/ Internet Explorer)and enter the following URL in the address bar:"localhost/test/index.php". This will run the PHP code and display the message "Hello world!" in your web browser .
Congratulations you have successfully Run your first PHP code on your PC/Computer.With this basic setup you can now begin to learn more about PHP and Start building your own web applications .
2.Variables:
In PHP variables re used to store values.Variables can be assigned a value using the $ symbol followed by the variable name . Example : <!DOCTYPE html>
<html>
<body>
<?php
$name = "John";
$age = 30;
$height = 1.75;
$is_student = true;
?>
<?php echo $name; ?><br>
<?php echo $age; ?><br>
<?php echo $height; ?><br>
<?php echo $is_student; ?>
</body>
</html>
In this example four variables are defined: $name, $age, $height and $is_student. The variable $name is assigned the value "John" $age is assigned the value 30 $height is assigned the value 1.75 and $is_student is assigned the value true. Note that PHP is a loosely typed language, which means that the data type of a variable is determined automatically based on the value assigned to it.
3.Data Types:
PHP has several data types including:- Strings: a sequence of characters enclosed in quotes. Example : "Hello world!"
- Integers: whole numbers without a decimal point. Example: 42
- Floats: numbers with a decimal point. Example: 3.14
- Booleans: true or false. Example: true
- Arrays: a collection of values indexed by a key. Example: $colors = array("red", "green", "blue");
- Objects: a complex data type that represents a realworld object.
<!DOCTYPE html>
<html>
<body>
<?php
$name = " John ";
$age = 30;
?>
<?php echo " Hello my name is $name and I m $age years old . "; ?>
</body>
</html>
In the above code , we define two variables using PHP.$name is a string datatype and is assigned the value "John" while $age is an integer datatype and is assigned the value 30. Using the echo statement we print a greeting to the screen that includes the values of these variables. The output of the code will be "Hello , my name is John and I am 30 years old". This simple example demonstrates how to define variables and output their values using PHP.
4.Operators:
PHP has several operators including:1.Arithmetic operators: used to perform mathematical operations , such as addition (+), subtraction (-), multiplication (*), division (/) and modulus (%) .
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 3;
echo $x + $y; //Outputs 13
echo $x - $y; // Outputs 7
echo $x * $y; //Outputs 30
echo $x / $y; // Outputs 3.3333333333333
echo $x % $y; // Outputs 1
?>
</body>
</html>
2.Assignment operators : used to assign a value to a variable . Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 3;
$x += $y; // equivalent to $x = $x + $y;
$x -= $y; // equivalent to $x = $x - $y;
$x *= $y; // equivalent to $x = $x * $y;
$x /= $y; // equivalent to $x = $x / $y;
$x %= $y; // equivalent to $x = $x % $y;
?>
</body>
</html>
3.Comparison operators : used to compare two values . Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 3;
var_dump($x == $y); // Outputs bool(false)
var_dump($x != $y); // Outputs bool(true)
var_dump($x > $y); // Outputs bool(true)
var_dump($x < $y); // Outputs bool(false)
var_dump($x >= $y); // Outputs bool(true)
var_dump($x <= $y); // Outputs bool(false)
?>
</body>
</html>
4.Logical operators : used to combine two or more conditions . Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 3;
$z = 5;
var_dump($x > $y && $x > $z); // Outputs bool(true)
var_dump($x > $y || $x < $z); // Outputs bool(true)
var_dump(!($x > $y)); // Outputs bool(false)
?>
</body>
</html>
5.Control Structures:
Control Structures In PHP re Used to execute code based on certain conditions .If-else statements : used to execute code if a certain condition is true or execute a different code if the condition is false. Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 3;
if ($x > $y) {
echo "x is greater than y";
} else {
echo "x is less than or equal to y";
}
//Outputs x is greater than y
?>
</body>
</html>
Switch statements : used to execute different code blocks based on the value of a variable . Example:
<!DOCTYPE html>
<html>
<body>
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is monday";
break;
case "Tuesday":
echo "Today is tuesday";
break;
case "Wednesday":
echo "Today is wednesday";
break;
default:
echo "Today is not monday, tuesday or wednesday";
}
//Outputs Today is monday
?>
</body>
</html>
Loops: used to execute a block of code multiple times . Here are some examples:
<!DOCTYPE html>
<html>
<body>
<?php
// While loop
$i = 1;
while ($i <= 10) {
echo $i;
$i++;
}
?> //Outputs 12345678910
<br> <?php
// Do-while loop
$i = 1;
do {
echo $i;
$i++;
} while ($i <= 10);
// For loop
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
?> //Outputs 1234567891012345678910
<br><?php
// Foreach loop (used to loop through arrays)
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
echo $color;
}
?> //Outputs RedGreenBlue
</body>
</html>
6.Functions:
Functions in PHP are used to perform specific tasks and can be reused throughout your code. Here 's an example of a function that calculates the sum of two numbers :
<!DOCTYPE html>
<html>
<body>
<?php
function sum($x, $y) {
$result = $x + $y;
return $result;
}
echo sum(2, 3);
?> // Outputs 5
</body>
</html>
In this example a function called 'sum ' is defined that takes two parameters $x and $y calculates their sum and returns the result using the return statement. The function is then called with the arguments 2 and 3 and the result is printed using the echo statement.
Functions can also have default parameter values which are used if no value is passed in for that parameter:
<!DOCTYPE html>
<html>
<body>
<?php
function sayHello($name = "World") {
echo "Hello, $name!";
}
sayHello();
sayHello("John");
?> // Outputs "Hello World!"
// Outputs "Hello John!"
</body>
</html>
In this example a function called sayHello is defined that takes an optional parameter $name with a default value of "World" . If a value is passed in for $name that value is used , otherwise the default value is used. The function is then called twice once with no argument and once with the argument "John" , and the output is printed using the echo statement.
7.Arrays:
Arrays in PHP are used to store multiple values in a single variable. Here 's an example of an array:
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue");
echo $colors[0]; // Outputs "red"
echo $colors[1]; // Outputs "green"
echo $colors[2]; // Outputs "blue"
?>
</body>
</html>
In this example an array called $colors is defined that contains three elements . The elements are accessed using their index , which starts at 0.
Arrays can also be created using the array function :
<!DOCTYPE html>
<html>
<body>
<?php
$ages = array("Peter" => 32, "John" => 28, "Mary" => 45);
echo $ages["John"]; // Outputs 28
?>
</body>
</html>
In this example an array called $ages is defined using key-value pairs . The elements are accessed using their key which is a string .
Arrays can be looped through using the foreach loop :
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color;
}
// Outputs RedGreenBlue
?>
</body>
</html>
In this example the array $colors is looped through using the foreach loop and each element is printed using the echo statement.
8.File Handling:
File handling in PHP is used to read and write files on a server . The fopen function is used to open a file and returns a file pointer that is used to access the file. Here 's an example of reading a file: Create a new file and name it "example.txt".Type "Hello World My name is Jhon" into the file and save the file .
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("example.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
}
// Outputs Hello World My name is Jhon
?>
</body>
</html>
In this example the fopen function is used to open a file called example.txt in read mode . The while loop is used to read each line of the file using the fgets function and output it using the echo statement. Finally the fclose function is used to close the file .
writing to a file is also possible Using the fopen function in write mode :
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("example.txt", "w");
fwrite($file, "Hello World!");
fclose($file);
?>
</body>
</html>
In this example, the fopen function is used to open a file called example.txt in write mode. The fwrite function is used to write the string "Hello World!" to the file, and the fclose function is used to close the file.
9. Database Connectivity:
PHP is often used for web development, and it 's common to interact with databases to store and retrieve data. PHP provides several extensions to interact with databases including MySQL and PostgreSQL.
In a previous post about MySQL, we discussed how to create a database and table. In this post we will provide a summary of those steps and explain how to create a database using phpMyAdmin .
In this post we will explain how to create a database using phpMyAdmin which is a popular webbased tool for managing MySQL databases. With phpMyAdmin you can easily create and manage databases , tables and other database objects.
You can create a new database by following these Steps:
- Click on the "New" button in the left hand navigation menu to create a new database.
- Enter a name for your database in the "Create database" form.You can choose any name you like but it ' s a good idea to choose something descriptive and easy to remember.
- Select the default collation for your database. This specifies the character set and sorting order that should be used for text data in your database. In most cases , you can leave this set to the default value of "utf8_general_ci".
- Click the "Create" button to create your new database.
Once you have created your database , you can start creating tables by following these steps:
- Click on the name of the database you just created to enter it.
- Click on the "New" button in the left hand navigation menu to create a new table.
- Enter a name for your table in the "Create table" form. Again , it 's a good idea to choose a descriptive name that reflects the purpose of your table.
- Enter the number of Columns you want your table to have.Each column represents a different Type of data that you want to store in the table.
- For each column, enter a name and select a data type. The data type determines the kind of data that can be stored in the column. For example , you might use an "int" data type for numeric values or a "varchar" data type for text strings.
- You can also specify additional options for each column, such as whether it should be a primary key (which uniquely identifies each row in the table), or whether it should have a default value or be set to auto-increment.
- Once you have defined all of your columns and their options, click the "Save" button to create your new table.
That's it! You have now created a new database and table using phpMyAdmin. From here, you can start populating your table with data, running queries and managing your database in a variety of other ways.
To create a table named "users" with three columns - "id", "name" and "email" - using phpMyAdmin, you can follow these steps:
Open phpMyAdmin and select the database where you want to create the "users" table.You can select the database by clicking on its name in the left-hand sidebar.
Click on the "Structure" tab at the top of the page to create a new table.
In the "Create table" section, enter "users" in the "Table name" field.
Under "Number of columns" , enter "3".
In the first row of the "Column name" column, enter "id".
In the "Type" column for the "id" column select "INT" for integer.
Check the "A.I." (Auto Increment) checkbox to make the "id" column an autoincrementing field.
In the "Attributes" section for the "id" column, select "Primary" to make it the primary key of the table.
Repeat steps 5-8 for the "name" and "email" columns.
Click on the "Save" button at the bottom of the page to create the "users" table with the specified columns.
That 's it! You have now successfully created a new table named "users" with three columns using phpMyAdmin. You can now start populating the table with data by using the "Insert" tab in phpMyAdmin or by using SQL statements to insert data directly into the table.
Insert query
To insert data into the "users" table using SQL queries in PHP You can use The following code :
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "myDataB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert data into the table
$sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
// Close connection
$conn->close();
?>
//Outputs new record created successfully
</body>
</html>
This code creates a new connection to your MySQL database using the connection variables (servername, username, password, dbname), and then inserts a new record into the "users" table with the values "John " for the "name" column and "john@example.com" for the "email" column.
SELECT query
Here 's an example of connecting to a MySQL database and executing a query:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "myDataB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute query
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
// Output results
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . " - Email: " . $row["email"];
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
?>
//Outputs Name: John - Email: john@example.com
</body>
</html>
In this Example, a connection to a MySQL database is established using the mysqli extension. The connect_error property is used to check if the connection was successful.The query method is used to execute a SQL query, and the fetch_assoc method is used to retrieve each row of the result set. Finally , the close method is used to Close the connection.
UPDATE query
To update an existing record in the "users" table using an SQL query in PHP you can use the following code as an example:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "myDataB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Update record in the table
$sql = "UPDATE users SET name='Jane Ross', email='jane.ross@example.com' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
// Close connection
$conn->close();
?>
//Outputs record updated successfully
</body>
</html>
In this Example , the code connects to the MySQL database using the connection variables (servername, username, password , dbname) and then updates the record with an "id" value of 1 in the "users" table to set the "name" to "Jane Ross" and The "email" to "jane.ross@example.com" .
You can modify the sql query to update different records in the table with different values.You can use various SQL operators and conditions to specify which records you want to update. For Example , you can use the WHERE clause to Specify a condition that must be met for the record to be updated .
DELETE query
To delete a record from the "users" table using an SQL query in PHP you can use the following code as an example :
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "myDataB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Delete record from the table
$sql = "DELETE FROM users WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
// Close connection
$conn->close();
?>
//Outputs record deleted successfully
</body>
</html>
In this Example , the code connects to the MySQL database using the connection variables (servername, username, password , dbname), and then deletes the record with an "id" value of 1 from the "users" table.
You can modify the SQL query to delete different records from the table based on different conditions. For example you can use the WHERE clause to specify a condition that must be met for the record to be deleted .
PHP is a versatile programming language used for web development, file handling and database connectivity. With a solid understanding of the basics covered in this article, you'll be well on your way to building web applications and working with databases in PHP.The next post promises to be an exciting one as we delve into the world of object-oriented programming (OOP) in PHP. With this , you can expect to gain a deeper understanding of PHP and MySQL and be better equipped to develop small applications. OOP is an essential programming concept that makes code more organized, easier to maintain, and helps reduce errors. So be sure to tune in for the next post to enhance your PHP development skills and take your coding abilities to the next level.