FahmidasClassroom

Learn by easy steps

P11 2

PHP is a popular server-side programming language. The basics of the PHP programming with MySQL database have been shown in this tutorial by using XAMPP server. Before practicing the examples of this tutorial, you have to install the XAMPP server and start the Apache and MySQL server.

Contents:

01. Create and execute the first PHP file
02. Use PHP with HTML script
03. Use of PHP variables
04. Print output in PHP
05. Use of conditional statement in PHP
06. Use of loop in PHP
07. PHP functions
08. Read user input using PHP
09. Create MySQL database with a table
10. Make database connection using PHP script
11. Insert data into the table
12. Read all data of the table
13. Search data in the table
14. Update data of the table
15. Delete data from the table

Create and execute the first PHP file

After installing the XAMPP, the htdocs folder is created under the c:/xampp/ location by default on windows operating system. Create a PHP file named firstscript.php with the following content by using any code editor and save he file inside the htdocs folder or any folder under the htdocs folder.

<?php
     //Print a simple text
     echo "My first PHP script!";
?>

Open any browser and go to the following URL address if the PHP file is stored in the htdocs folder.

http://localhost/firstscript.php

The following output will appear after executing he PHP file.

P1 3

Go to top

Use PHP with HTML script

Create a PHP file with the following script that uses the HTML tags inside the PHP script. The uses of PHP variables with some HTML tags and simple inline CSS code have been shown in the script.

<html>
<body>
<!-- PHP script -->	
<?php
      //Declare a string variable
      $lang = "PHP";
      //Give a line break
      echo "<br>";	
      //Print a text with HTML tags, PHP variable, and CSS
      echo "<center><h2>My favorite language is <strong style='color:BLUE'>$lang</strong></h2></center>";
?>
</body>
</html>

The following output will appear after executing the above script. The text is printed as the heading and the value of the PHP variables is printed with blue color font by using CSS.

P2 4

Use of PHP variables

PHP is a weakly typed language that does not require any data type declaration to declare any type of variable. String, number, Boolean, array and object variables can be defined in the PHP script. Four types of scalar variables, one array variable, and a constant variable have been declared in the following script. Next, the values of these variables have been printed.

<?php

//Declare string variable
$book_name = "Head First PHP & MySQL";
//Declare integer variable
$published_year = 2024;
//Declare float variable
$price = 55.89;
//Declare boolean variable
$available = 1;
//Declare array variable
$authors = array("Lynn Beighley", "Michael Morrison");
//Declare constant variable
define("L", "PHP");

//Print all variables
echo L," is popular scripting language. Many books available on ", L," programming.<br>
One of the PHP book details is mentioned below.<br>";
echo "Book Name: $book_name<br>";
echo "Publishing Year: $published_year<br>";
echo "Price: $price<br>";
if ($available) echo "Available: Yes<br>";
else echo "Available: No<br>";  
echo "Authors: $authors[0] and $authors[1]";
?>

The following output will appear after executing the above script.

P3 2

Go to top

Print output in PHP

Various built-in functions exist in PHP to print the output in the browser. The uses of echo and printf functions with variable and without variable have been shown in the following script.

<?php

//Print a simple text message
echo "Learn PHP in an hour<br>";
printf ("%s\n","Learn PHP in an hour");

//Declare PHP variables
$lang = "PHP";
$hours = 1;

//Declare text with PHP variables
echo "<br>Learn $lang in $hours hour.<br>";
printf ("Learn %s in %d hour.\n", $lang, $hours);

?>

The following output will appear after executing the script. The first two lines have shown the output without any PHP variable and the last two lines have shown the output with PHP variables.

P4 1

Go to top

Use of conditional statement in PHP

PHP supports two types of conditional statements like other programming languages. One is ‘if’ statement and another is ‘switch-case’ statement. The uses of these statements have been shown in the following script.

<?php

//Declare a variable
$age = 30;

//Simple if condition
if ($age >= 20) 
{
    echo "<br>You are eligible for the exam.";
}

//Simple if-else condition
if ($age < 20) 
{
echo "<br>You are not eligible for the exam.";
} 
else 
{
     echo "<br>You are eligible for the exam.";
}

//Simple if-elsif-else condition 
if ($age < 15) 
{
    echo "<br>You are in group-1";
} 
else if($age < 25) 
{
    echo "<br>You are in group-2";
}
else 
{
    echo  "<br>You are in group-3";
}


//Switch-case statement
switch ($age) 
{
    case 10:
    case 11:
    case 12:
    case 13:
    case 14:
        echo "<br>You are in group-1";
        break;
    case 15:
    case 16:
    case 17:
    case 18:
    case 19: 
        echo "<br>You are in group-2";
        break;
    default:
        echo "<br>You are not eligible for the exam.";
}

?>

Here, the first three lines have shown the output of the ‘if’ statement and the last line has shown the output of the ‘switch-case’ statement.

P5

Go to top

Use of loop in PHP

Four types of loop can be used in the PHP script. These are ‘while’, ‘do-while’, ‘for’, and ‘foreach’ loop. The uses of these loops have been shown in the following output.

<?php

//Use of while loop
$num = 10;
while ($num > 0) {
     echo "$num ";
     $num--;
}

echo "<br>";

//Use of do-while loop
$num = 10;
do {
      echo "$num ";
      $num++;
} while ($num <= 15);

echo "<br>";

//Use of for loop
for ($num = 5; $num >= 0; $num--) 
{
     echo "$num ";
}

echo "<br>";

//Use of foreach loop
$numbers = array(67, 34, 23, 54);
foreach ($numbers as $num) {
     echo "$num ";
}

?>

Four loops will be generated the following output.

P6 2

Go to top

PHP functions

The uses of the global and local variables with a function have been shown in the following script. If the variable of the same name is defined as a global and a local variables in PHP then the global variable will not be effected by the local variable. Here, $name variable has been declared as global variable at the beginning of the script and $name variable has been defined inside the function that is local variable.

<?php

//Global variable
$name = "Fahmida";

//Define a function with an argument                                                                                   
function count_length ($name) {

    echo "Author's name is $name.<br>";
    $name = "Yesmin";
    echo "Author's modified name is $name.<br>";
}

//Call the function
count_length($name);
//Print the global variable
echo "Author's name is $name.<br>";

?>

According to the output, the global variable is not effected by the local variable.

P7

Go to top

Read user input using PHP

There are two ways to take input in the PHP script. One way is to use $_GET[] variable that read data from the URL. Another way is to use $_POST[] variable that read data from the HTML form. The uses of these variables have been shown in the following script. One value has been read by the $_GET[] variable and two values have been read by the $_POST[] variables.

<?php 
//Read the value from the URL
if (isset($_GET['id'])) $id = $_GET['id'];
else $id = 0;
if ($id == 2 || $id == 5)
{
    echo "You are selected.";
}
else{
    echo "You are not selected.";
}
?>
<!-- HTML Form -->
<form action=# method='post'>
<p>Name: <input type='text' name='n' />
<p>Email: <input type='email' name='e' />
<p> <input type='submit' name='sub' value='Submit' />
</form>

<?php
//Read data submitted by HTML form
if (isset($_POST['sub']))
{
    echo "Name: ", $_POST['n'], "<br>";
    echo "Email: ", $_POST['e'], "<br>";
}
?>

If the 2 is passed as the id value in the URL then ‘You are selected.’ message will be appeared in the output.

P8 0

Type the values in two textboxes and press the Submit button.

P8 1 2

The following output will appear after pressing the Submit button.

P8 2 1

Go to top

Create MySQL database and a table

You can create database and table by executing the query from the MySQL command prompt or by using any GUI of the MySQL server. Here, phpmyadmin has been used as MySQL GUI. Go to the following URL to open phpmyadmin in the browser.

http://localhost/phpmyadmin

Click on the SQL tab and write the following statements to create a database named ‘library’ and a table named ‘books’ inside this database.

CREATE DATABASE library;
USE library;
CREATE TABLE books(
    id INT NOT NULL PRIMARY KEY,
    title VARCHAR(50),
    author VARCHAR(70),
    publication VARCHAR(60));

Go to top

Make database connection using PHP script

Different ways exist in PHP to make database connection with the MySQL database. The following script will create database connection with the ‘library’ database by creating the object of the PHP mysqli class. Next, it has been checked that the database connection is established successfully or not.

<?php

//Define the connection variables
$hostname = "localhost";
$user = "root";
$pass = "";
$database = "library";

//Create database object
$db_connection = new mysqli($hostname, $user, $pass, $database);

//Check the database connection
if ($db_connection->connect_error) 
{
     echo "<br><h2>Unable to make the database connection.</h2>";
}
else
     echo "<br><h2>Database connected successfully.</h2>";
?>

?>

The following output will appear if the database is connected successfully.

P10

Go to top

Insert data into the table

The way of executing the INSERT query by using PHP script has been shown in the following script. One record will be inserted into the ‘books’ table after executing the script.

<?php

//Create database object
$db_connection = new mysqli("localhost", "root", "", "library");

//Check the database connection
if ($db_connection->connect_error) 
{
     echo "<br><h2>Unable to make the database connection.</h2>";
}
else
{
    //Insert query 
    $query = "INSERT INTO books(id, title, author, publication) values(1, 'Learn PHP', 'Lerry', 'Apress')";

    if ($db_connection->query($query))
        echo "1 record inserted into the table.<br>";
    else 
        echo "Error inserting data.<br> ";

    $db_connection->close();
}
     
?>

The following output will appear if the insert query is executed successfully.

P11 1

P11 2

Go to top

Read all data of the table

The way of reading all records from the ‘books’ table by using PHP script has been shown in the following script. All records of the ‘books’ table will be printed after executing the script.

<?php

//Create database object
$db_connection = new mysqli("localhost", "root", "", "library");

//Check the database connection
if ($db_connection->connect_error) 
{
     echo "<br><h2>Unable to make the database connection.</h2>";
}
else
{
    //Select query 
    $query = "SELECT * FROM books";

    $result = $db_connection->query($query);

    if ($result->num_rows > 0) 
    {
         //Read all records read by the query
         while($row = $result->fetch_assoc()) 
         {
             echo "Book Name: ".$row["title"]."<br>Author Name: " . $row["author"]."<br>";
         }
    } 
    else 
    {
         echo "No data found. <br>";
    }

    //Close connection
    $db_connection->close();
}
     
?>

The ‘books’ table contains only one record that is printed here.

P12

Go to top

Search data in the table

The way of searching a particular record based on the search word has been shown in the following script. The search word will be taken by using a HTML form and check the word exists in the ‘title’ or ‘author’ or ‘publication’ field of the ‘books’ table. If the search result returns true then the book title and the author name will be printed.

<html>
<body>

<form action=# method="post">
Search <input type="text" name="search"> &nbsp;&nbsp;&nbsp;
<input type ="submit">
</form>

<?php

if(isset($_POST['search']))
     $src = $_POST['search'];
else
     $src = "";

//Create database object
$db_connection = new mysqli("localhost", "root", "", "library");

//Check the database connection
if ($db_connection->connect_error) 
{
     echo "<br><h2>Unable to make the database connection.</h2>";
}
else
{
    //Retrieve data based on the search value
    $query = "select * from books where title = '$src' or author = '$src' or publication = '$src'";
    $result = $db_connection->query($query);

    if ($result->num_rows > 0) 
    {
         //Read all records read by the query
         while($row = $result->fetch_assoc()) 
         {
             echo "Book Name: ".$row["title"]."<br>Author Name: " . $row["author"]."<br>";
         }
    } 

    //Close connection
    $db_connection->close();
}
     
?>

</body>
</html>

Type the search word in the textbox and click on the Submit button.

P13 1

If the search word is ‘Learn PHP’ that exists in the table data then the following output will appear.

P13 2

Go to top

Update data of the table

The way of updating the particular record from the ‘books’ table by using PHP script has been shown in the following script. The record of the ‘books’ table will be updated if the matching id value exists in the table.

<?php

//Create database object
$db_connection = new mysqli("localhost", "root", "", "library");

//Check the database connection
if ($db_connection->connect_error) 
{
     echo "<br><h2>Unable to make the database connection.</h2>";
}
else
{
    //Update query 
    $query = "UPDATE books set title = 'Learn MySQL', author = 'Marry', publication = 'ORelly' WHERE id = 1";

    if ($db_connection->query($query))
        echo "1 record updated.<br>";
    else 
        echo "Error updating data.<br> ";

    $db_connection->close();
}
     
?>

The following output will appear if the record is updated.

P14

Go to top

Delete data from the table

The way of deleting the particular record from the ‘books’ table by using PHP script has been shown in the following script. The record of the ‘books’ table will be deleted if the matching id value exists in the table.

<?php

//Create database object
$db_connection = new mysqli("localhost", "root", "", "library");

//Check the database connection
if ($db_connection->connect_error) 
{
     echo "<br><h2>Unable to make the database connection.</h2>";
}
else
{
    //Delete query 
    $query = "DELETE FROM books WHERE id = 1";

    if ($db_connection->query($query))
        echo "1 record deleted.<br>";
    else 
        echo "Error deleting data.<br> ";

    $db_connection->close();
}
     
?>

The following output will appear if the record is deleted.

P15

Go to top

Conclusion:

The reader will be able to do web programming by using PHP and MySQL after reading this tutorial properly.