Wednesday, April 23, 2025

MySQL SHOW, USE, DESCRIBE

The command "SHOW DATABASES" is used to list all the databases that are available in the MySQL server: 


mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql>

In this case, the output shows four databases: information_schema, mysql, performance_schema, and sys. These are system databases that are created automatically when MySQL is installed.

The information_schema database contains information about the MySQL server, such as database metadata, table metadata, and user privileges.

The mysql database contains user account information and other system-level data.

The performance_schema database contains performance-related data, such as statistics on queries and locks.

The sys database is used by MySQL Workbench to provide additional functionality for database administration. 


mysql> SHOW DATABASES \g
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql>

This is the same MySQL command as before, which shows the list of databases in the current MySQL instance. The only difference is that the "\g" character sequence is used at the end of the command instead of a semicolon (;).

The "\g" sequence can be used to terminate a command and send it to the server for execution. It is an alternative to using a semicolon as a command terminator. When the "\g" sequence is used, the output of the command is displayed immediately after the command is executed, rather than waiting for the server to return control.

In this case, the output is the same as before, showing the four system databases that are available in the MySQL server. 


mysql> USE mysql;
Database changed
mysql>

This is the output of a MySQL command that changes the current database context to the "mysql" database. The "USE" command is used to select a database in MySQL.

The command "USE mysql" is executed, which selects the "mysql" database. The output shows that the database has been changed successfully.

Once a database is selected using the "USE" command, all subsequent commands that operate on tables or data in the database will be executed in the context of that database, unless a different database is selected using the "USE" command again.


mysql> SHOW TABLES FROM mysql;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| component                 |
| db                        |
| default_roles             |
| engine_cost               |
| func                      |
| general_log               |
| global_grants             |
| gtid_executed             |
| ...                       |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
33 rows in set (0.08 sec)

mysql>

The "SHOW TABLES" command is used to display a list of all the tables in a particular database.

The command "SHOW TABLES FROM mysql" is executed, which lists all the tables that exist in the "mysql" database. The output shows a list of table names, each on a separate line, that includes system tables such as "user", "db", "tables_priv", "columns_priv", and others.

These tables store information about user accounts, permissions, databases, and other metadata that are used by the MySQL server to manage and secure the system. 


mysql> DESCRIBE user;
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                    | Type                              | Null | Key | Default               | Extra |
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                     | char(255)                         | NO   | PRI |                       |       |
| User                     | char(32)                          | NO   | PRI |                       |       |
| Select_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Insert_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Update_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Delete_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Create_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| ...                      | ...                               | ...  |     | ....                  |       |
| password_lifetime        | smallint unsigned                 | YES  |     | NULL                  |       |
| account_locked           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_role_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_role_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Password_reuse_history   | smallint unsigned                 | YES  |     | NULL                  |       |
| Password_reuse_time      | smallint unsigned                 | YES  |     | NULL                  |       |
| Password_require_current | enum('N','Y')                     | YES  |     | NULL                  |       |
| User_attributes          | json                              | YES  |     | NULL                  |       |
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
51 rows in set (0.10 sec)

mysql>

The DESCRIBE statement is used to display the structure or schema of a table in a MySQL database. It shows the column names, data types, and any constraints on the columns such as primary key, foreign key, and nullability.

In our example, the DESCRIBE statement is used to display the structure of the user table in the mysql database. It shows that the table has 51 columns, including columns for the username, host, and various privileges. It also shows additional columns for password policies and user attributes.

MySQL Server Installation

MySQL Introduction

Tuesday, April 22, 2025

PHP Write, Append to Files

You are advised to check corresponding YouTube video at the end of this article. 


<?php

$result = fopen("new_file.txt" , "w") or 
die ("Unable to create that file");

fwrite($result, "Write this to file \n");

fclose($result);

?>

This code creates a new file named "new_file.txt" and opens it for writing, using the fopen() function with the "w" mode, which means that the file will be created if it doesn't exist, or truncated to zero length if it already exists.

If the file cannot be created or opened for writing, the or die() statement is executed, which will print the specified error message ("Unable to create that file") and terminate the script immediately.

The fwrite() function is then used to write the string "Write this to file" to the opened file handle ($result). The "\n" at the end of the string represents a newline character, which will create a new line in the file.

Finally, the fclose() function is used to close the file handle, which flushes any pending writes to disk and releases the system resources associated with the file. 


<?php

$result = fopen("new_file.txt" , "a") or 
die ("Unable to create that file");

fwrite($result, "Append this to file \n");

fclose($result);

?>

This PHP code opens a file named "new_file.txt" and appends the string "Append this to file" followed by a newline character to the end of the file.

The fopen function is used to open the file in "append" mode, which means that data will be written to the end of the file instead of overwriting the existing content. The "a" mode flag is used to open the file in append mode.

Then, the fwrite function writes the string "Append this to file" followed by a newline character to the file. The file is then closed using the fclose function.

This code is useful for adding new content to an existing file without overwriting the existing data in the file.

form.html to pass things to .php file


<form action="grabthings.php" method="post">
<label>New Line:</label>
<input type="text" name="new_line">
<br><br>

<input type="submit" value="Submit">
</form>

This code creates an HTML form with one text input field named "new_line" and a submit button. When the user fills out the input field and clicks the submit button, the form data is sent to a PHP script called "grabthings.php" using the HTTP POST method. The value entered in the input field will be accessible in the PHP script using the $_POST superglobal variable.

grabthings.php


<?php 

$get_new_line = $_POST["new_line"];

$out = fopen("output.txt", "a") or 
die ("Can't append to output.txt");

fwrite($out, $get_new_line . "\n");

fclose($out);

?>

The value of the "new_line" input field is obtained using the $_POST superglobal variable and stored in the $get_new_line variable. The code then opens the "output.txt" file in append mode using the fopen() function, which creates the file if it does not exist. If the file cannot be opened, the script terminates and outputs an error message.

The fwrite() function is used to write the value of $get_new_line to the end of the "output.txt" file. The "\n" character is added to create a new line in the file.

The fclose() function is used to close the file handle and release the resources associated with it.

PHP Reading Files

You are advised to check corresponding YouTube video at the end of this article.

There are several file handling functions in PHP, but some of the most commonly used ones are:

  1. fopen(): Used to open a file and returns a file pointer resource that is used in other file handling functions.

  2. fclose(): Used to close an opened file.

  3. fwrite(): Used to write data to an opened file.

  4. fread(): Used to read data from an opened file.

  5. file_get_contents(): Used to read the entire contents of a file into a string.

  6. file_put_contents(): Used to write a string to a file.

  7. file_exists(): Used to check if a file exists.

  8. unlink(): Used to delete a file.

These functions allow developers to create, read, update, and delete files in PHP.

source.txt


first line
second line
third line

index.php or open_file.php, you decide.


<?php

$result = fopen("source.txt" , "r");

echo fread($result, filesize("source.txt"));

fclose($result);

?>

This code opens the file "source.txt" in read mode using the fopen() function, reads the content of the file using the fread() function, and then closes the file using the fclose() function.

The fread() function reads the content of the file up to the specified number of bytes, which is determined by the filesize() function that returns the size of the file in bytes.

The content of the file is then output to the screen using the echo statement.

This code can be used to display the content of the file "source.txt" on a web page. 


<?php

$result = fopen("source.txt" , "r");

echo fgets($result) . "<br>";
echo fgets($result) . "<br>";
echo fgets($result) . "<br>";

fclose($result);

?>

This code reads and outputs the first three lines of the "source.txt" file using the fgets() function. Here's what's happening:

  • fopen("source.txt" , "r"): This opens the "source.txt" file in read mode and returns a file pointer to the beginning of the file. This file pointer is stored in the $result variable.
  • fclose($result): This closes the file and frees up the file pointer.

So, assuming the "source.txt" file has at least three lines of text, this code will output those three lines to the screen. 


<?php

$result = fopen("source.txt" , "r");

for ($x = 0; $x < 5; $x = $x + 1) {
	echo fgets($result)	. "<br>";
}

fclose($result);

?>

This code opens the file "source.txt" for reading and then reads and outputs the first 5 lines of the file using a for loop and the fgets function.

The fgets function reads a line from the file pointed to by the file handle ($result in this case) and returns it as a string. Each time the function is called, it reads the next line from the file.

In this code, the fgets function is called 5 times inside a for loop that runs 5 times. Each time the loop runs, it calls fgets to read the next line and then outputs that line with an HTML line break (<br>). 


<?php

$result = fopen("source.txt" , "r");

$x = 0;

while ($x < 4) {
	echo fgets($result) . "<br>";
	$x = $x + 1;
}

fclose($result);

?>

Note that the loop condition checks if $x is less than 4 because the loop should only run for 4 iterations to print the first 4 lines. 


<?php

$result = fopen("source.txt" , "r");

while (!feof($result)) {
	echo fgets($result) . "<br>";
}

fclose($result);

?>

The feof() function in PHP checks if the end of the file has been reached while reading a file using a file pointer. It stands for "end of file".

The feof() function takes one argument, which is the file pointer returned by fopen() when opening a file. It returns true if the file pointer has reached the end of the file, and false otherwise.

A common use of feof() is to read a file line by line using a loop and fgets(), and terminate the loop when feof() returns true, indicating the end of the file has been reached. 


<?php

$result = fopen("source.txt" , "r") or 
die ("Unable to find that file");

while (!feof($result)) {
	echo fgets($result) . "<br>";
}

fclose($result);

?>

If the file does not exist or cannot be opened for any reason, the code after the 'or' operator will be executed, which in this case is the die() function with an error message "Unable to find that file". The die() function will terminate the execution of the script immediately and display the error message.

PHP Include, Require

You are advised to check corresponding YouTube video at the end of this article.

Include and "require" are language constructs that allow you to include the contents of one file in another PHP file.

The difference between the two is that require will generate a fatal error if the file to be included cannot be found, while include will only generate a warning and continue execution of the script.

We use include and require to break up our code into smaller, reusable components. For example, we might put our database connection code into a separate file and then include it in all the files that need to access the database. This way, if we need to change the database connection details, we only need to make the change in one place.

It's smart to use include and require when you have common code that needs to be shared across multiple files, or when you want to modularize your code into smaller, more manageable chunks. It can also improve code organization and readability.

navigation.php


<?php 
echo '
<a href="">Home</a> - 
<a href="">Products</a> - 
<a href="">About</a> - 
<a href="">Contact</a>';

?>

This is an example of creating a navigation menu using HTML and PHP code. It creates a simple horizontal menu with four links: Home, Products, About, and Contact. The HTML code is enclosed in a PHP echo statement, which allows it to be dynamically generated by PHP code.

The links can be replaced with actual URLs to make the menu functional.

index.php


<!DOCTYPE html>
<html lang="en">
<head></head>
<body>

<h1>Main Heading on Home Page</h1>

<?php include 'navigation.php'; ?>

<p>Main Content</p>
<p>Main Content</p>
<p>Main Content</p>
<p>Main Content</p>

<?php include 'navigation.php'; ?>

</body>
</html>

This code includes the navigation.php file twice in an HTML page. The navigation.php file contains the navigation menu links that are included in both instances on the page.

Using include allows you to reuse code across multiple pages, which can be helpful for maintaining consistency and reducing redundancy. It's smart to use include when you have common HTML or PHP code that you need to use across multiple pages.

In this case, including the navigation menu twice may not be necessary, but it could be useful if you want to show the same menu at the top and bottom of the page for easy navigation.

index.php


<!DOCTYPE html>
<html lang="en">
<head></head>
<body>

<h1>Main Heading on Home Page</h1>

<?php include 'navigation.php'; ?>

<p>Main Content</p>
<p>Main Content</p>
<p>Main Content</p>
<p>Main Content</p>

<?php require 'navigation_1.php'; ?>

<p>Main Content</p>
<p>Main Content</p>
<p>Main Content</p>
<p>Main Content</p>

</body>
</html>

The include statement is used to include the navigation.php file, which contains the navigation links for the website. This code will be inserted at the location where the include statement is written.

The require statement is also used to include another file navigation_1.php, which may contain some critical code or data. If the file is not found, the script execution will stop with a fatal error. It is recommended to use require instead of include for important files, as it ensures that the file is present and can be accessed before continuing with the script.

In this particular example, both include and require are used for the same file, which may not make sense, but it's just for demonstration purposes.

PHP Constants

You are advised to check corresponding YouTube video at the end of this article.

Constants are fixed values that do not change during the execution of a program. Once defined, a constant retains its value throughout the entire program and cannot be modified by the program or the user.

Constants are useful in situations where you need to use a value that remains the same throughout the program, such as mathematical constants (e.g., pi), physical constants (e.g., speed of light), or configuration values (e.g., database credentials).

In many programming languages, constants are typically defined using the const or define keyword and are given a name and a value. Once defined, the constant can be used throughout the program using its name, and its value cannot be changed or modified. 


<?php 

define("SYSTEM_ver", "SAP v0.5");
define("LEGAL", "Please, read TOS");
define("NOTICE", "You will be kicked after 3 failed logins");
define("HR", "<hr>");

echo SYSTEM_ver;
echo HR;

echo LEGAL;
echo HR;

echo NOTICE;
echo HR;

?>

This code defines four constants using the define() function and then uses them to output messages with a horizontal line separator between them.

The first constant is SYSTEM_ver with the value of "SAP v0.5", which could be used to identify the version number of the system. The second constant is LEGAL with the value of "Please, read TOS", which could be used to display a legal notice or terms of service. The third constant is NOTICE with the value of "You will be kicked after 3 failed logins", which could be used to warn users about login attempts.

The last constant is HR with the value of "<hr>", which is an HTML horizontal line element. This constant is used to separate each message with a horizontal line, making the output more readable. 


<?php 

define("SYSTEM_ver", "SAP v0.5");
define("LEGAL", "Please, read TOS");
define("NOTICE", "You will be kicked after 3 failed logins");
define("HR", "<hr>");

function message() {
	echo SYSTEM_ver;
	echo HR;

	echo LEGAL;
	echo HR;

	echo NOTICE;
	echo HR;
}

message();

?>

Explanation:

  • The define() function is used to define constants in PHP.
  • In this example, we define four constants: SYSTEM_ver, LEGAL, NOTICE, and HR.
  • We then create a function message() that simply echoes these constants.
  • Finally, we call the message() function, which outputs the values of the constants with horizontal lines in between them.

PHP Return Values

You are advised to check corresponding YouTube video at the end of this article.

A return value is the value that a function or method returns after performing its operations or calculations. When a function is called, it can execute a series of instructions and then return a value to the caller, which can then be used in the program.

Return values are important because they allow you to get output from a function or method and use it in your program. They also allow you to make decisions and perform operations based on the output of a function or method.

In most programming languages, you can use the "return" keyword to specify the return value of a function. 


<?php 

function addition($x, $y) {
	$result = $x + $y;
	
	return $result;	
}

//Function ok, but we are not using return at all
addition(5, 6);

//Let's use return
echo addition(5, 6);
echo "<br>";

echo addition(3, 6);
echo "<br>";

echo addition(1, 7);
echo "<br>";

?>

Tthe function addition accepts two parameters and calculates their sum.

Using the return statement to return a value from a function is important because it allows the value to be used later in the program. In this example, without the return statement, the calculated result would be lost and could not be used elsewhere in the program.

By using return, the value can be stored in a variable, printed to the screen, or used in any other way that is necessary.

PHP Default Arguments

You are advised to check corresponding YouTube video at the end of this article.


<?php 

function one_ping($host = "google.com") {
	echo "<pre>";
	system ("ping ". $host);
	echo "</pre>";
}

one_ping("yahoo.com");

?>

The function "one_ping" has a default argument of "google.com" assigned to the parameter $host. This means that if an argument is not passed when the function is called, it will use "google.com" as the default value for the $host parameter.

Using default arguments in functions can be useful in situations where you want to provide a default value for a parameter, but still allow the user to override it if needed. This can make the function more flexible and easier to use.

PHP Function Arguments

You are advised to check corresponding YouTube video at the end of this article.

The terms "parameter" and "argument" are often used interchangeably, but there is a slight difference between them.

A parameter is a variable or a placeholder in a function definition that represents the input that the function expects. It is a part of the function's signature and defines the type and order of the input that the function expects.

An argument, on the other hand, is the actual value that is passed into a function when it is called. It is the data that is supplied to the function for it to work on.

To put it simply, a parameter is what a function expects, while an argument is what a function receives.

The reason why we pass arguments to functions is to provide input data to the function so that it can perform a task based on that input data. For example, if you are writing a function that calculates the area of a rectangle, you would need to pass the length and width of the rectangle as arguments to the function so that it can perform the calculation.

Passing arguments to functions makes your code more flexible and reusable, as you can use the same function to perform the same task with different input data. It also helps to reduce code duplication, as you can create a function that performs a task and then call that function multiple times with different arguments.

In addition, passing arguments to functions allows you to separate the input data from the logic of the function. This makes your code easier to read, understand, and maintain, as the function only needs to focus on performing the task, while the input data is handled separately. 


<?php 

function one_ping($host) {
	echo "<pre>";
	system ("ping ". $host);
	echo "</pre>";
}

one_ping("google.com");

?>

This is a PHP code that defines a function called "one_ping" and then calls it with the argument "google.com".

The function "one_ping" takes one parameter, which is the hostname or IP address of the host that you want to ping. The function uses the "echo" statement to print the opening "<pre>" tag, which formats the output as preformatted text, and then uses the "system" function to execute the "ping" command on the specified host. The output of the "ping" command is then printed to the screen.

The "ping" command sends a network packet to the specified host to test the network connection and measures the time it takes for the packet to be sent and received. The output of the "ping" command shows the number of packets sent and received, the percentage of packet loss, and the time it took to send and receive each packet.

The last line of the code calls the "one_ping" function by using its name followed by parentheses and passing the argument "google.com", which executes the function and prints the output to the screen. In this case, the output will be the result of the "ping" command on the host "google.com".

By defining a function, you can reuse the code to ping different hosts by passing different arguments to the function. This makes the code more modular and easier to maintain.

form.html


<form action="grabthings.php" method="post">
<label>Host to Ping:</label>
<input type="text" name="host">
<br><br>

<input type="submit" value="Submit">
</form>

This is an HTML code that creates a form with a text input field and a submit button.

The form uses the "post" method to send the data to the "grabthings.php" file when the user clicks the submit button. The "action" attribute specifies the URL of the file that will handle the form submission.

The form contains a label that says "Host to Ping" and a text input field with the name "host". When the user types a value into the text field and submits the form, the value will be sent to the server as a POST parameter with the name "host".

The submit button has the text "Submit" and will submit the form when clicked.

grabthings.php


<?php 

$get_host = $_POST["host"];

function one_ping($x) {
	echo "<pre>";
	system ("ping ". $x);
	echo "</pre>";
}

one_ping($get_host);

?>

This is a PHP code that retrieves the value of the "host" parameter from the form submission using the $_POST superglobal variable, assigns it to the variable $get_host, and then calls the "one_ping" function with $get_host as the argument.

The "one_ping" function takes one parameter, which is the hostname or IP address of the host that you want to ping. The function uses the "echo" statement to print the opening "<pre>" tag, which formats the output as preformatted text, and then uses the "system" function to execute the "ping" command on the specified host. The output of the "ping" command is then printed to the screen.

By passing the value of the "host" parameter to the "one_ping" function as an argument, the function will ping the host that was entered into the text field on the form submission.

Note that this code assumes that the form was submitted using the "post" method and that the name attribute of the text input field is "host".

PHP Functions

You are strongly advised to check corresponding YouTube video at the end of this article.

A function is a block of code that performs a specific task or set of tasks. It is like a subprogram that can be called from different parts of a program. A function can take inputs, perform operations on those inputs, and return a result.

Functions are used in programming to organize code, make it more modular, and improve code reuse. By breaking a program into functions, you can isolate specific tasks and make them easier to understand and maintain. Functions also enable you to write code that is more concise and readable by reducing duplication and promoting abstraction.

In many programming languages, including Python, Java, C++, and JavaScript, functions are defined using a specific syntax that includes a name, a set of parameters (if any), and a block of code.

A parameter is a variable that is used to pass data into a function. It is a way for the function to receive input values from the caller.

When a function is defined, you can specify one or more parameters inside the parentheses after the function name. The parameters are separated by commas, and each parameter is given a name.

A default parameter is a parameter in a function that has a predefined value. If the caller does not provide a value for that parameter when calling the function, the default value is used instead.

Default parameters are useful when you want to make a parameter optional or when you want to provide a default behavior for a parameter. They can help to simplify function calls by reducing the number of arguments that need to be specified.

The parentheses "()" are used to define the parameters of a function and to call the function with those parameters.

When you define a function, the parentheses are used to declare the parameters that the function will receive. The parameters are placed inside the parentheses, separated by commas, and can have default values assigned to them if needed.

When you call a function, you also use the parentheses to pass arguments to the function.  


<?php 

function print_3_times() {
	echo "Dude, where's my car ? <br>";	
	echo "Dude, where's my car ? <br>";	
	echo "Dude, where's my car ? <br>";	
}

print_3_times();

?>

This is a script that defines a function called "print_3_times" and then calls it.

The function "print_3_times" uses the "echo" statement to print the text "Dude, where's my car ?" three times, each followed by a line break "<br>".

The last line of the code calls the function by using its name followed by parentheses, which executes the function and prints the output to the screen. In this case, the function will print the text "Dude, where's my car ?" three times. 


<?php 

function print_3_times() {
	echo "Dude, where's my car ? <br>";	
	echo "Dude, where's my car ? <br>";	
	echo "Dude, where's my car ? <br>";	
}

function call_other_functions() {
	print_3_times();
	print_3_times();
	print_3_times();
	print_3_times();	
}

call_other_functions();

?>

This is a script that defines two functions and then calls one of them.

The first function, "print_3_times", uses the "echo" statement to print the text "Dude, where's my car ?" three times, each followed by a line break "<br>".

The second function, "call_other_functions", calls the "print_3_times" function four times, which will result in the text "Dude, where's my car ?" being printed 12 times in total.

The last line of the code calls the "call_other_functions" function, which executes it and prints the output to the screen. 


<?php 

function custom_pinger() {
	echo "<pre>";
	system("ping google.com");
	echo "</pre>";
}

custom_pinger();

?>

This is a PHP code that defines a function called "custom_pinger" and then calls it.

The function "custom_pinger" uses the "echo" statement to print the opening "<pre>" tag, which formats the output as preformatted text, and then uses the "system" function to execute the "ping" command on the domain "google.com". The output of the "ping" command is then printed to the screen.

The "ping" command sends a network packet to the specified domain to test the network connection and measures the time it takes for the packet to be sent and received. The output of the "ping" command shows the number of packets sent and received, the percentage of packet loss, and the time it took to send and receive each packet.

The last line of the code calls the "custom_pinger" function by using its name followed by parentheses, which executes the function and prints the output to the screen. In this case, the output will be the result of the "ping" command on the domain "google.com".

Note that the "system" function allows you to execute commands on the operating system, which can be a security risk if the input is not properly validated. You should be careful when using the "system" function and ensure that it is only used with trusted input.

PHP While, Do While

You are strongly advised to check corresponding YouTube video at the end of this article.

While and do..while are loop structures in programming languages that allow a piece of code to be executed repeatedly until a certain condition is met.

The while loop executes a block of code while a condition is true. It first evaluates the condition, and if it is true, it enters the loop and executes the block of code. Once the code is executed, it evaluates the condition again, and if it's still true, it executes the code again, repeating this process until the condition becomes false. If the condition is initially false, the block of code is not executed at all.

The do..while loop is similar to the while loop, but the block of code is executed at least once before the condition is evaluated. First, the block of code is executed, and then the condition is evaluated. If it is true, the loop executes again, repeating the process. If it's false, the loop terminates.

While loops are useful when we don't know in advance how many times we need to execute a block of code, and do..while loops are useful when we want to ensure that a block of code is executed at least once. 


<?php 

$x = 0;

while ($x < 10) {
	echo "Right now: $x <br>";
	$x = $x + 1;
}

/*
for ($x = 0; $x < 10; $x = $x + 1) {
	echo "Right now: $x <br>";	
}
*/

?>

This code is an example of a while loop in PHP. The loop executes the code inside its block as long as the condition $x < 10 is true.

The code initializes a variable $x to 0 before entering the loop. Inside the loop, it first prints the value of $x using the echo statement. Then, it increments the value of $x by 1 using the $x = $x + 1 statement. This process repeats until the value of $x is no longer less than 10, at which point the loop ends.

This code is functionally equivalent to the commented-out for loop that appears at the bottom of the script.

The for loop is another type of loop that is often used for iterating over a sequence of values. In this case, the for loop initializes the variable $x to 0, checks the condition $x < 10, and increments the value of $x by 1 with each iteration, just like the while loop.

However, the for loop includes all three of these steps in its header, making it a more concise way to express this type of loop. 


<?php 

$x = 0;

do {
	echo "Right now: $x <br>";
	$x = $x  + 1;
} while ($x < 10);

?>

This PHP script demonstrates the use of a "do-while" loop.

The code inside the curly braces will be executed at least once, regardless of the condition specified in the while statement.

In this example, the variable $x is initialized to zero, and the loop will execute until $x is no longer less than 10. During each iteration, the value of $x is echoed to the screen along with some text. The value of $x is then incremented by 1.

The loop will continue to execute until the value of $x is 10 or greater.

PHP Associative Arrays

You are advised to check corresponding YouTube video at the end of this article. 

Associative arrays in PHP are arrays that use named keys instead of numerical indexes. Each key in the array is associated with a specific value. They are also commonly referred to as "hashes" or "dictionaries" in other programming languages.

In an associative array, the keys can be any valid string or integer, and each key is unique within the array. You can access the values of an associative array by specifying the corresponding key, rather than an index number.


<?php 

$fruits = array("Apples" => 5, "Oranges" => 12, "Grapes" => 25);

echo "Amount of Apples: " . $fruits["Apples"] . "<br>";
echo "Amount of Oranges: " . $fruits["Oranges"] . "<br>";
echo "Amount of Grapes : " . $fruits["Grapes"] . "<br>";

?>

This PHP script initializes an associative array called $fruits with three key-value pairs: "Apples" => 5, "Oranges" => 12, and `"Grapes" => 25". The keys of the array are the names of the fruits, and the values represent the number of fruits available.

Then, the script uses the keys to access the values stored in the associative array using the square brackets notation. It prints out the number of Apples, Oranges, and Grapes using the echo statement. 

The "=>" operator is used in associative arrays to assign a value to a specific key. The key is placed on the left side of the => operator, and the corresponding value is placed on the right side of the => operator. It is a way to define key-value pairs in an array. In the example above, the keys are "Apples", "Oranges", and "Grapes", and the corresponding values are 5, 12, and 25, respectively.


<?php 

$fruits = array("Apples" => 5, "Oranges" => 12, "Grapes" => 25);

$len_of_fruits = count($fruits);

echo "Num of elements: " . $len_of_fruits . "<br><br>";

foreach ($fruits as $key => $value) {
	echo "In array: $key, amount: $value <br>";
}

?>

This PHP script creates an associative array $fruits with three key-value pairs. The keys are the names of different fruits and the values represent the number of those fruits.

Then the script uses the count() function to get the number of elements in the array and prints it out.

After that, the script uses a foreach loop to iterate over each key-value pair in the array. Within the loop, the variable $key represents the key (fruit name) and $value represents the value (number of fruits). The script prints out the key and value for each iteration of the loop.

This way of iterating over an associative array in PHP is commonly used when you need to work with both the keys and values of the array.

PHP Sorting Arrays

You are advised to check corresponding YouTube video at the end of this article. 


<?php 

$fruits = array("Bananas", "Oranges", "Apples", "Grapes");

echo "BEFORE: <br>";
foreach ($fruits as $x) {
	echo "Element: $x <br>";
}

echo "<br><hr><br>";

sort($fruits);
echo "AFTER: <br>";
foreach ($fruits as $x) {
	echo "Element: $x <br>";
}

?>

This PHP script creates an array of fruits and then sorts the elements in alphabetical order using the sort() function.

The foreach loop is used to display the array elements before and after sorting.

In the first loop, the script prints the elements of the $fruits array as they are stored. In the second loop, the script sorts the $fruits array using the sort() function and then prints the sorted elements.

The output of the script will display the original order of the elements in the array followed by the sorted order of the elements.

PHP Count Function

You are advised to check corresponding YouTube video at the end of this article.

In PHP, count() is a built-in function that is used to count the number of elements in an array or the number of characters in a string. It returns the number of elements in an array or the length of a string. 


<?php 

$languages = array("Javascript", "Perl", "Lisp", "C++", "Python");

$num_of_languages = count($languages);

echo "Number of langs: " . $num_of_languages;

?>

This is a PHP script that creates an array named $languages with five elements: "Javascript", "Perl", "Lisp", "C++", and "Python".

The count() function is then used to count the number of elements in the $languages array, which is five. The result is then stored in a variable called $num_of_languages.

Finally, the script outputs the result to the screen using the echo statement, which prints the string "Number of langs: " concatenated with the value of $num_of_languages, which is "5" in this case. 


<?php 

$languages = array("Javascript", "Perl", "Lisp", "C++", "Python");

$num_of_languages = count($languages);

for ($x = 0; $x < $num_of_languages; $x = $x + 1) {
	echo "Lang at the moment: $languages[$x] <br>"; 
}

?>

This PHP script creates an array called $languages containing five different programming languages. It then uses the count() function to determine the number of elements in the $languages array and stores that value in the $num_of_languages variable.

Next, it uses a for loop to iterate through the array. The loop initializes the $x variable to 0, and then loops as long as $x is less than $num_of_languages. Inside the loop, it uses the $x variable to access each element of the array in turn, and then prints out a message that includes the current element of the array.

The output of this script will be five lines of text, each one displaying one of the programming languages in the $languages array. 


<?php 

$languages = array("Javascript", "Perl", "Lisp", "C++", "Python");

$num_of_languages = count($languages);

foreach ($languages as $lang) {
	echo "Lang at the moment: $lang <br>";
}

?>

This script uses a foreach loop to achieve the same thingas before. The loop iterates over the $languages array, and each time it goes through the loop, it assigns the current element's value to the variable $lang. The loop then prints out the value of $lang.

This is a more concise and often easier to read way of iterating over an array in PHP

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...