News:

Alert!!! HTML Evaluation 01- Quiz

Main Menu

Recent posts

#1
PHP TUTORIAL / PHP Loop: 016
Last post by Cohort Master - May 01, 2024, 10:35 AM
In the following chapters you will learn how to repeat code by using loops in PHP.

Often when you write code, you want the same block of code to run over and over again a certain number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

In PHP, we have the following loop types:

while - loops through a block of code as long as the specified condition is true.
do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true.
for - loops through a block of code a specified number of times.
foreach - loops through a block of code for each element in an array.

The specificity of this lesson using while loop is to show you in a glance how to loop our data from database table to your webpage as an admin or controller.

Instead of going to Phpmyadmin to view if data was inserted we can call the data to our page in a tabler form.

First create your database connection using the code below and save it with
Quoteconfig.php

<?php
define
('DB_SERVER','localhost');
define('DB_USER','root'); // default username is root for offline server
define('DB_PASS' ,''); //password must be empty since you are working offline
define('DB_NAME''database_name'); // input your database name that you created 
$con mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
 echo 
"Failed to connect to MySQL: " mysqli_connect_error();
}
?>


The MySQL select function and while loop command

<table>
<tr>
<th>#</th>
<th>Fullname</th>
<th>Email</th>
<th>Phone Number</th>
<th>Time Regd.</th>
</tr>
           
<?php 
                  
                  $sql 
"SELECT * from table_name ORDER BY 'id' ASC";
              
// To call all registered investors
$result mysqli_query($con$sql);
$cnt=1;
while(
$row mysqli_fetch_array($resultMYSQLI_ASSOC))
{
  
?>

<tr>
<th><?php echo ($cnt);?></th>
<th><?php echo ($row['fullname']);?></th>
<th><?php echo ($row['email']);?></th>
<th><?php echo ($row['phone']);?></th>
<th><?php echo ($row['time']);?></th>
</tr>
<?php $cnt=$cnt+1;} ?>
</table>

The above while loop will be repeating it's command once new info is being added to the database.

The information in the table above is changeable to suite your database and table info.

QuoteHow to echo time format <?php echo htmlentities($row['time']); ?>

Full code
<td><?php $go3date('d, M Y'); $v3htmlentities($row['time']); echo date('d, M Y'strtotime($v3));?></td>


STATUS AUTOMATION
To set your code to echo Active or Live if the status reports 1 else show Inactive or Block if the status reports 0.
<td><?php $suc=$row['status']; if($suc== "") { echo '<span class="text-primary">Inactive</span>'; } ?> <?php if($suc=="Credited") { echo '<span class="text-success">Credited</span>'; } ?></td>
#2
PHP TUTORIAL / PHP Login: 015
Last post by Cohort Master - Apr 17, 2024, 03:29 AM
MySQL is a popular choice as a backend database for PHP powered web applications. In this chapter, we shall learn to develop a login page for a PHP application that authenticates the given username and password.

You should have a web server having PHP and MySQL installed for experimenting with the example discussed in this chapter. The bundled binaries of Apache, PHP and MySQL (MariaDB) in the form of XAMPP for your operating system can be easily installed.


The first part of PHP login application is to establish database connection object. We use myqli API to obtain connection object. Save following code as "config.php"
<?php
define
('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME''demos');
$con mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
 echo 
"Failed to connect to MySQL: " mysqli_connect_error();
}
?>

This PHP script is called inside the login script. It presents the user with a HTML form to enter username and password. In case the form is submitted, PHP runs a SELECT query to retrieve a row in the admin table where the username and passcode matches with the user inputs.

If the row count is one, it indicates that the username and the password entered matches. The username is save to the $_SESSION variable and the browser is directed to welcome.php script

Login.php
Save the following code as "login.php" −
<?php

session_start
();

include_once(
"config.php");

if(isset(
$_POST['login']))

{
$email=$_POST['email'];

$password=md5($_POST['password']);

$retmysqli_query($con,"SELECT * FROM userregistration WHERE email='$email' and password='$password'");
$num=mysqli_fetch_array($ret);
$status=$num['status'];
if(
$num>0)
{

if(
$status==0)
{
$_SESSION['action1']="Verify  your Email Id by clicking  the link In your mailbox";
}
else {
$_SESSION['login']=$email;
$_SESSION['id']=$num['id'];
$_SESSION['name']=$num['name'];
$extra="welcome.php";
$host=$_SERVER['HTTP_HOST'];
$uri=rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("location:http://$host$uri/$extra");
exit();
}
}
else
{
$_SESSION['action1']="Invalid username or password";
$extra="login.php";
$host  $_SERVER['HTTP_HOST'];
$uri  rtrim(dirname($_SERVER['PHP_SELF']),'/\\');

header("location:http://$host$uri/$extra");

exit();

}

}

 
?>

To echo failed session attempts if login fails due to incorrect information:
<?php echo $_SESSION['action1']; ?><?php echo $_SESSION['action1']="";?>
Welcome.php or Dashboard.php
The "welcome.php" script gets invoked when the user is authenticated. It reads the session variable to display a welcome message.
<?php
session_start
();
include_once(
"config.php");
if(
$_SESSION['login'])
{
 
?>

Insert the above code to secure the welcome or dashboard page. It can only be opened to login users.

Session is used to store user's information to PHP hence the browser closes. To kill session is to either log out or close browser
<?php echo $_SESSION['name']; ?>
To echo login user name etc.

Logout.php
Finally, the logout script removes the destroys the session and redirects the user to the login page.
<?php
session_start
();
$_SESSION['login']=="";
session_unset();
$_SESSION['action1']="You have logged out successfully..!";
?>

<script language="javascript">
document.location="login.php";
</script>

Password Encryption
To encrypt your password to secure it from being seen or hacked. It is advised to encrypt all passwords in the registration page before sending it to the database.
$password=md5($_POST['password']);

Good luck!!
#3
PHP TUTORIAL / PHP MySQL Create Table: 014
Last post by Cohort Master - Apr 01, 2024, 08:40 AM
A database table has its own unique name and consists of columns and rows.

Create a MySQL Table Using MySQLi
The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname", "email" and "reg_date":
QuoteWe will be creating the table below directly from Mysqli database
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

PHP MySQL Insert Data
Insert Data Into MySQL Using MySQLi
After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

The SQL query must be quoted in PHP
String values inside the SQL query must be quoted
Numeric values must not be quoted
The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

In the previous chapter we created an empty table named "MyGuests" with five columns: "id", "firstname", "lastname", "email" and "reg_date". Now, let us fill the table with data.
QuoteNote: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default update of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.

The following examples add a new record to the "MyGuests" table:
<?php
$servername 
"localhost";
$username "username";
$password "password";
$dbname "myDB";

// Create connection
$conn = new mysqli($servername$username$password$dbname);
// Check connection
if ($conn->connect_error) {
  die(
"Connection failed: " $conn->connect_error);
}

$sql "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')"
;

if (
$conn->query($sql) === TRUE) {
  echo 
"New record created successfully";
} else {
  echo 
"Error: " $sql "<br>" $conn->error;
}

$conn->close();
?>
#4
PHP TUTORIAL / PHP Connect to MySQL: 013
Last post by Cohort Master - Apr 01, 2024, 08:20 AM
QuoteNote: Before connecting to Mysql ot database, it is imperative to start up your xampp engine.

PHP 5 and later can work with a MySQL database using:

MySQLi extension (the "i" stands for improved)
PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.

Should I Use MySQLi or PDO?
If you need a short answer, it would be "Whatever you like".

Both MySQLi and PDO have their advantages:

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.

So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the entire code - queries included.

Both are object-oriented, but MySQLi also offers a procedural API.

Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.

QuoteNote: For this tutorial, we will be working only with MySqli.

CONNECTING SETUP
Example (MySQLi Procedural)
<?php
$servername 
"localhost";
$username "username";
$password "password";

// Create connection
$conn mysqli_connect($servername$username$password);

// Check connection
if (!$conn) {
  die(
"Connection failed: " mysqli_connect_error());
}
echo 
"Connected successfully";
?>

QuoteClick the next class to learn about to create a database table.
#5
PHP TUTORIAL / PHP MySQL Database: 012
Last post by Cohort Master - Apr 01, 2024, 08:11 AM
With PHP, you can connect to and manipulate databases.

MySQL is the most popular database system used with PHP.
What is MySQL?
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL uses standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter:

The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows.

Databases are useful for storing information categorically. A company may have a database with the following tables:
  • Employees
  • Products
  • Customers
  • Orders

Database Queries
A query is a question or a request.
We can query a database for specific information and have a recordset returned.
Look at the following query (using standard SQL):
SELECT LastName FROM Employees
The query above selects all the data in the "LastName" column from the "Employees" table.
#6
PHP TUTORIAL / PHP Include Files: 011
Last post by Cohort Master - Apr 01, 2024, 07:56 AM
The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.

Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.

PHP include and require Statements
It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement.

The include and require statements are identical, except upon failure:

1. require will produce a fatal error (E_COMPILE_ERROR) and stop the script
2. include will only produce a warning (E_WARNING) and the script will continue


Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header needs to be updated, you can only update the header include file.

Syntax
include 'filename';

or

require 'filename';

PHP include Examples
Example
Assume we have a standard footer file called "footer.php", that looks like this:
<html>
<body>

<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</body>
</html>

QuoteCREATIVITY is one of the facets of web development.
#7
PHP TUTORIAL / PHP Date and Time: 010
Last post by Cohort Master - Apr 01, 2024, 07:37 AM
The PHP date() function is used to format a date and/or a time.

The PHP Date() Function
The PHP date() function formats a timestamp to a more readable date and time.

Get a Date
The required format parameter of the date() function specifies how to format the date (or time).

Here are some characters that are commonly used for dates:

d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional formatting.

The example below formats today's date in three different ways:
<?php
echo "Today is " date("Y/m/d") . "<br>";
echo 
"Today is " date("Y.m.d") . "<br>";
echo 
"Today is " date("Y-m-d") . "<br>";
echo 
"Today is " date("l");
?>


Formatting the Dates and Times with PHP
The format parameter of the date() function is in fact a string that can contain multiple characters allowing you to generate a date string containing various components of the date and time, like day of the week, AM or PM, etc. Here are some the date-related formatting characters that are commonly used in format string:

d - Represent day of the month; two digits with leading zeros (01 or 31)
D - Represent day of the week in text as an abbreviation (Mon to Sun)
m - Represent month in numbers with leading zeros (01 or 12)
M - Represent month in text, abbreviated (Jan to Dec)
y - Represent year in two digits (08 or 14)
Y - Represent year in four digits (2008 or 2014)
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/), or spaces to add additional visual formatting.

Similarly you can use the following characters to format the time string:

h - Represent hour in 12-hour format with leading zeros (01 to 12)
H - Represent hour in in 24-hour format with leading zeros (00 to 23)
i - Represent minutes with leading zeros (00 to 59)
s - Represent seconds with leading zeros (00 to 59)
a - Represent lowercase ante meridiem and post meridiem (am or pm)
A - Represent uppercase Ante meridiem and Post meridiem (AM or PM)
PHP Tip - Automatic Copyright Year
Use the date() function to automatically update the copyright year on your website:

Example
Copyright 2010-<?php echo date("Y");?>
#8
PHP TUTORIAL / PHP Form Handling: 009
Last post by Cohort Master - Apr 01, 2024, 07:23 AM
The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:
<html>
<body>

<form action="welcome.php" method="POST">
Name: <input type="text" name="name" id="name"><br>
E-mail: <input type="email" name="email" id="email"><br>
<input type="submit">
</form>

</body>
</html>

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables.

The "welcome.php" looks like this:
<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

The output could be something like this:
Welcome John
Your email address is john.doe@example.com

The same result could also be achieved using the HTTP GET method you just have to change the POST to GET

GET vs. POST
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

QuoteDevelopers prefer POST for sending form data.
#9
PHP TUTORIAL / PHP if...else Statements: 008
Last post by Cohort Master - Apr 01, 2024, 06:52 AM
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that condition is false.

Syntax
<?php
if (condition) {
  
// code to be executed if condition is true;
} else {
  
// code to be executed if condition is false;
}
?>

Example
Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
<?php
$t 
date("H");

if (
$t "20") {
  echo 
"Have a good day!";
} else {
  echo 
"Have a good night!";
}
?>

PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.

Syntax
if (condition) {
  code to be executed if this condition is true;
} elseif (condition) {
  // code to be executed if first condition is false and this condition is true;
} else {
  // code to be executed if all conditions are false;
}

Example
Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

<?php
$t 
date("H");

if (
$t "10") {
  echo 
"Have a good morning!";
} elseif (
$t "20") {
  echo 
"Have a good day!";
} else {
  echo 
"Have a good night!";
}
?>
#10
PHP TUTORIAL / PHP if...else Statements: 008
Last post by Cohort Master - Apr 01, 2024, 06:49 AM
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that condition is false.

Syntax
<?php
if (condition) {
  
// code to be executed if condition is true;
} else {
  
// code to be executed if condition is false;
}
?>

Example
Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
<?php
$t 
date("H");

if (
$t "20") {
  echo 
"Have a good day!";
} else {
  echo 
"Have a good night!";
}
?>

PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.

Syntax
if (condition) {
  code to be executed if this condition is true;
} elseif (condition) {
  // code to be executed if first condition is false and this condition is true;
} else {
  // code to be executed if all conditions are false;
}

Example
Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

<?php
$t 
date("H");

if (
$t "10") {
  echo 
"Have a good morning!";
} elseif (
$t "20") {
  echo 
"Have a good day!";
} else {
  echo 
"Have a good night!";
}
?>