Wednesday, 20 September 2017

How To Create A Random Background Color Using Php 

The following Script shows You how To Generate a "Random Background color". A random background color can be created with an "Array Function", and a little bit of CSS...


<?php
$colors = array ("red","green","cyan","blue","lightblue","brown","purple");
?>
<!DOCTYPE html>
<html>
<head land="en">
    <title>HELLO WORLD</title>
</head>
<style>
 body{
     background-color:<?php echo $colors[rand(0,count($colors)-1)]?>;
 }
 .area{
     width: 1000px;
     height:3000px;
     background-color:<?php echo $colors[rand(0,count($colors)-1)]?>;
     margin-left:0;
 }
</style>
    <body>
      <div class="area"></div>
    </body>
</html>

Trying this makes it easier for you to create a "Random Background color".

Monday, 18 September 2017

Cookies and Sessions - The PHP way

 Cookies and Sessions - The PHP way

What are cookies?

A cookie is a small file created by a website and is usually stored by the browser in hard disk, they contain information about the user and/or user preferences. Cookies are used to store user states. 
You can locate cookies on your chrome browser by:

1. Open settings


2. Click privacy and security
3. Navigate to content settings

4. Click cookies

5. Finally, scroll down until you find the list of cookies currently stored on your system


How to set up a Cookie in PHP

A cookie is created with the setcookie() function. The usual syntax is 
setcookie($name, $value, $expire, $path, $domain, $secure, $httponly). Note that $name is the only required parameter, the other parameters are optional.
When the setcookie() function is called , a superglobal variable called $_COOKIE is formed. This variable is an associative array consisting of all the cookie attributes.
Let's create a simple cookie
1. create a php file and enter the following code:

<?php

$name = "first_cookie";
$val = "My very first cookie";
$expire = time() + (24*60*60);//The cookie expires in 24 hours
setcookie($name, $val, $expire);


?>
With this, you've created a cookie. We can view the content of the cookie using the echo() function as shown below: 
 <?php

$name = "first_cookie";
$value = "My very first cookie";
$expire = time() + (24*60*60);//The cookie expires in 24 hours
setcookie($name, $value, $expire);
echo $_COOKIE["first_cookie"];
?>

Unsetting a cookie

Unsetting a cookie is just as easy as setting one. To do it one has to set value of the cookie to null and the expiry time to any period in the past.
This can be achieved with a simple line of code:

setcookie($c_name, null, time() -360)

Let's add this to our PHP file, do not forget to  comment out the set cookie function.
<?php

$name = "first_cookie";
$value = "My very first cookie";
$expire = time() + (24*60*60);//The cookie expires in 24 hours
//setcookie($name, $value, $expire);
setcookie($name, null, time() -360);

if (isset($_COOKIE["first_cookie"])){
echo $_COOKIE["first_cookie"];
}else{
echo "cookie unavailable";
}
?>
When you refresh the page 
You have successfully created a deleted a cookie.

Sessions

A session is a server side stored information that exist while a user continues to interact with a website.

Setting up a session

A session on is set using the session_start() php function.
<?php

session_start();
$_SESSION['name'] = 'My_session';
echo $_SESSION['name'] = 'My_session';

?>

The session_start() creates a superglobal called $_SESSION, this contains all the session variables. Note that endless variables can be created.
A session can be deleted by 

session_unset()
This deletes all the session variables

session_destroy()
This destroys the session

Differences Between Cookies and Sessions

Cookies are stored in the client side while sessions are stored on the server side. Sessions are more persistent than cookies. Also, cookies can be deleted from the browser.



How to Write a Php Script to Change the Background Colour on Page Reload

How to Write a PHP script that changes the Background colour on Page Refresh

Hello, i'm Majiyd and in this article, i',m going to show you how to write a simple PHP script that would change the background colour of your webpage anytime the page is reloaded.

First, we set up a simple index.php file and run on localhost

"<!DOCTYPE html> 
<html> 
   <head>    
     <meta charset="utf-8"> 
     <title>Changing the background colour</title>  
   </head>
  <body> 
    <p>The background colour of this page changes anytime this page is refreshed</p>
  </body> 
</html>"
Next, we add a php tag to the file and the initialise an array. In this array, we'll add all the colours that we want to background to be able to change to.

<?php      
$colours = array("red", "green", "blue", "white", "pink", "gold")    
?>

$colours is the array that consists of all the colours. Next, we initialise an integer $num which is the number of available colours.

<?php      
$colours = array("red", "green", "blue", "white", "pink", "gold");      
$num = count($colours) - 1;    
?>

Count is an in-built PHP function for getting the number of elements in an array. You probably noticed that we subtracted one from count($colours) to get $num, this is because in PHP, 0 is considered the first number, not 1.
Each colour in the $colours array can be printed to the screen by calling  $colours with an index corresponding to the position of the colour in the array. For example
$colours[0] refers to red
$colours[1] refers to green
$colours[5] refers to gold

A more practical example would be to execute the simple script show below
<?php      $colours = array("red", "green", "blue", "white", "pink", "gold");      $num = count($colours) - 1;  echo $colours[0];
          echo "<br/>"; 
 echo $colours[1];
              echo "<br/>";
 echo $colours[5];    ?>
The result is:

Now we change the background colour by echoing a random colour from our array into a css style tag present our page as shown below:

<?php  
 $colours = array("red", "green", "blue", "white", "pink", "gold");  
 $num = count($colours) - 1;  
 $background_colour = $colours[rand(0,$num)]; 
?> 
<!DOCTYPE html> 
<html> 
  <head>  
  <meta charset="utf-8">    
  <title>Changing the background colour</title>  
  <style type="text/css">  
    body{ 
      background-color: <?php echo $background_colour;?>  
    } 
  </style>  
</head>  
<body>  
  <p>The background colour of this page changes anytime this page is   refreshed</p>
</body>
 
</html>
 Each time you refresh this page, you'd get a different background colour






Wednesday, 13 September 2017

           How to Insert Data Into MySQL Using PHP

 This article teaches the basic steps on how to create and insert data into your MYSQL DATABASE..
following these steps make's it easier and quicker for you...
  • Open a new php file.
  • Start your server.
  • Create the html form.
  • Create a Database.
  • Create a connection to your Database file.
  • Connect your form to your database
  • Insert your Data to your form and submit

OPEN A NEW PHP FILE

Open your visual studio code or notepad++, create a new php file e.g form.php 

START YOUR SERVER


You must have installed either WAMPP, XAMPP, LAMP et. After the installation, you start any of the server that you are provided with.Example "localhost".


CREATE THE HTML < FORM>

The html <form> element are use to input users  input..The code below shows you an example of an html form.
 <!DOCTYPE html>
<html>
    <head>
       <title>My Form</title>
</head>
<body>
<form>
<fieldset>
<label>firstname<label/>
<input type="text" name="first_name" placeholder="first_name" ><br>

<label>lastname<label/>
<input type="text" name="last_name" placeholder="last_name"><br>

<label>gender<label/>
<input type="text" name="gender" placeholder="gender"><br>

<label>phone_num<label/>
<input type="text" name="phone_num" placeholder="phone no"><br>

<label>email<label/>
<input type="text" name="email" placeholder="email"><br>

<input type="submit" value="submit" name="submit">
        </fieldset>
</form>
</body>
</html>

CREATE A DATABASE 

A database consist of one or more tables.A database can be created by writing a MYSQL code.The following code shows you how to create a database which can be use to store data..

<?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 to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),

)";

if ($conn->query($sql) === TRUE) {
    echo "Table MyGuests created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

NOTE;
  • AUTO INCREMENT -  automatically increases the value by 1 each time a new record is added.
  • PRIMARY KEYS - the primary key of a relational table uniquely identifies each record in the table.
A database can also be created by typing the following parameters into your browser."localhost/phpmyadmin".phpMyAdmin is a free and open source administration tool for MySQL.




After loading the web page it shows you the picture above ↑.

   After opening the webpage You click on "NEW" to create a new database.You name your database and give it a collation of  your choice, as shown in the picture below.

   CREATE  A TABLE

When your database has been created, you will then have to create your table.As we all know that every tables contain rows and columns, as many as possible ,and every table created must also have an" id " mainly for identification of data stored in the table and other valuable information.eg "FIRST_ NAME","LAST_NAME"etc as shown in the image below.Note; your Id must be your "PRIMARY KEY" and must be set to  "AUTO_INCREMENT, also avoid white space while naming :correct:"last_name" :wrong:"last name"


CREATE A CONNECTION TO YOUR DATABASE FILE

To create a connection to your database file, you would have to write a php script, and the script will be written inside your php file.The following code shows you how to connect your database file.

<?php
    const DB_NAME="intro_php_mysql";//orany prefered name
    const DB_USER="root";
    const DB_PASS="";//input if u have set your password
    const DB_HOST="localhost";//your host is mainly localhost
    $connection=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if(!$connection){
    die("Database connection failed".mysqli_connect_error() ." ( ".mysqli_connect_errno() . ")");
}else{
    echo "Connection Successful!!";
}
?>

CONNECTING YOUR FORM TO YOUR DATABASE

Your form must be connected to your database, soo that any parameters that are inserted into the form will be saved successfully to your database.the code belo shows how to connect your form to your database.
<?php
require_once("database.php");//connection to your database file
if(!isset($_POST['submit'])){
        echo "you did not submit the form";
} else {
        if (trim($_POST['first_name']) == "" || trim($_POST['last_name'])== "" || trim($_POST['gender']) == "" ){
                echo " first name cannot be blank";
        } else{
                if (is_int(($_POST['first_name']))){
                        echo "first name cant be a number format";
                }else {
                         $first_name = $_POST["first_name"];
                         $last_name=$_POST["last_name"];
                         $gender=$_POST["gender"];
                         $phone_num = $_POST["phone_num"];
                         $email=$_POST["email"];
                        
                        $sql = " INSERT INTO assignment (";
                        $sql .= "first_name, last_name, phone_num, email";
                        $sql .= ")VALUES (";
                        $sql .="'{$first_name}', '{$last_name}', '{$phone_num}', '{$email}'";
                        $sql .= ")";

                        $result_set = mysqli_query( $connection , $sql);
                        if( mysqli_affected_rows($connection)> 0){
                                echo " Data was saved successfuly sir!!!";
                                  // redirection
                               // header("Location: twitter.php");
                             //exit;
                        } else{
                                echo "data not saved" . mysqli_error($connection);
                        }
                }       
        }
}
?>
<form action="form.php" method="post">
        <fieldset>

<label>firstname<label/>
<input type="text" name="first_name" placeholder="first_name" />

<label>lastname<label/>
<input type="text" name="last_name" placeholder="last_name"/>

<label>gender<label/>
<input type="text" name="gender" placeholder="gender"/>

<label>phone_num<label/>
<input type="text" name="phone_num" placeholder="phone no"/>

<label>email<label/>
<input type="text" name="email" placeholder="email"/>

<input type="submit" value="submit" name="submit"/>
        </fieldset>
</form>

Saturday, 9 September 2017

HOW TO USE PHP TO INSERT DATA INTO MYSQL DATABASE
To achieve these follow the following steps:
1.      Create a table
2.      Writing php code to INSET data into mysql database
3.      Confirming the success of your connection.
To create a table using my phpAdmin
Php myAdmin is the most simple setup that you can use for a table. Here are some analysis of the table.
  • Name – This is the name of your column. It will be displayed at the top of your table.
  • Type – You can set a column type here.
  • Length/Values – Used to specify the maximum length your entry in this column can have.
  • Index – We used “Primary” index for our “ID” field. When creating a table, it is recommended to have one ID column. It is used to enumerate table entries and required when configuring table relationships. I also marked “A_I”, which means Auto Increment.
Click Save and your table will be created.
Writing php code follow this:
<?php
const DB_USER= "root";
const DB_PASS= "";
const DB_SERVER= "localhost";
//create a database connection
$connection= mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);

if ($connection){
echo "successful";

}else {
die ("database cconnection failed".mysqli_connect_error()."(".mysqli_connect_error().")");
}
// Set the variables for the person we want to add to the database
$first_Name = "Maruf";
$last_Name = "Olawale";
$email = "sewen101@yahoo.com";
// Here we create a variable that calls the prepare() method of the database object
// The SQL query you want to run is entered as the parameter, and placeholders are written like this :placeholder_name
$my_Insert_Statement = $my_Db_Connection->prepare("INSERT INTO Students (name, lastname, email)VALUES (:first_name,:last_name, :email)");
// Now we tell the script which variable each placeholder actually refers to using the bindParam() method
// First parameter is the placeholder in the statement above - the second parameter is a variable that it should refer to
$my_Insert_Statement->bindParam(:first_name, $first_Name);
$my_Insert_Statement->bindParam(:last_name, $last_Name);
$my_Insert_Statement->bindParam(:email, $email);
// Execute the query using the data we just defined
// The execute() method returns TRUE if it is successful and FALSE if it is not, allowing you to write your own messages here
if ($my_Insert_Statement->execute()) {
  echo "New record created successfully";
} else {
  echo "Unable to create record";
}

?>

Friday, 8 September 2017

How to insert form data into a MySQL database using PHP



HOW TO INSERT FORM DATA INTO A MYSQL DATABASE USING PHP
This article assumes that you have a basic understanding of html and css, and you already know how to run a php script. This is a really easy if you follow these steps:
  1. Create a html form in your index.php
  2. Create database
  3. Create the table
  4. Create a connection to your database 
  5. Insert your data
  6. …aaand you’re done!


CREATE HTML FORM IN YOUR INDEX.PHP
Create a file called index.php in your local host directory and create a simple form in this page.

“ <form class="" action="index.php" method="post">
      <label for="firstname">Firstname</label>
      <input type="text" name="firstname" required placeholder="firstname"/><br><br>
      <label for="lastname">Lastname</label> 
<input type="text" name="lastname" required placeholder="lastname"/><br><br> 
      <label for="email">Phone Number</label>
      <input type="text" name="number" required placeholder="enter phone number"><br><br>

      <button type="submit" name="submit">Sign up</button> <br><br>
    </form> </body>”
Activate WAMP, LAMP or XAMMP server and enter “localhost” into your browser. You should see something like the image below:



CREATE DATABASE
To create a database, enter “localhost/phpmyadmin” into your browser


On the login page, enter “root” as the username if you haven’t used phpMyAdmin before. Otherwise, you can enter any other username that you may have created.
By default, the password should be left empty but if you have changed your password before enter the correct password.



On the left side of the phpMyAdmin page is a list of all the databases present on your server.
Click New and enter a name for your database. Note that
 I have named mine “Learning_insert”, change the collation to “utf8_unicode_ci” and then click “create”





CREATE THE TABLE
When the database is created you would be directed to a create table page, this is where we would create an empty table that we would fill up with data from our form.
Enter a name name a set the “number of colums” to 3. The reason for this is we’d be passing three sets of data (firstname, lastname, phonenumber) from our form to our db. Now click “go”.
Fill up the “Name” and set the “type” to “varchar” and the “length” to “255” set the storage engine to “innoDB” and the click save.




At this point, you have successfully created a database and a table.
You can view the content of your db by clicking the database name and the table. Ours is currently empty.


CREATE A CONNECTION TO YOUR DATABASE
Return to your index.php file and and add a php tag. All php scripts must be written in a php tag.
“<?php ?>”
A simple connection to our database “learning_insert” can be created using the php script below
“<head>
<?php
  //setting connection parameters
  CONST DBHOST = "localhost";
  CONST DBUSER = "root";  //or whichever username you created
  CONST PASSWORD = ""; //password is empty by default, enter yours if you have one
  CONST DBNAME = "learning_insert";

  //setting up connection
  $conn = mysqli_connect(DBHOST, DBUSER, PASSWORD, DBNAME);

  //confirm connection
  if(mysqli_connect_errno()){
   //if connection fails
    die('Failed to connect to db'.mysqli_connect_error().'('.mysqli_connect_errno().')');
  }else {
    echo  "connection successful";
  }
?>
</head>”
If you’re getting any errors, remember google is your friend. If your work is successful, you should see something like this. Note that "connection successful" would always be echoed to the screen. This is a useful testing feature, however, you can turn it off by commenting out the echo success message.

INSERT DATA
The first step to inserting data into the db is to check if the submit button has been pressed, if this condition is met we set up the variables that would be inserted into the db. This can be achieved by adding the following php code snippet to the php script in our header.
if (isset($_POST['submit'])){

        //if the submit button is pressed create variables
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $phonenumber = $_POST['number'];
}”
Finally, the data would be inserted into the db using the php code below



$sql =  "INSERT INTO `user_info ` (firstname, lastname, phonenumber) VALUES ('{$firstname}', '{$lastname}', '{$phonenumber}')"; //ensure  that this line of code is on the same line

if($insert = mysqli_query($conn, $sql)) {
                     echo “You have inserted data succesfully”;
                   }else{
                     echo "data not saved".mysqli_error($conn);
                   }



In the end, your full code should look just like this.

“<!doctype html>
<head>
<?php

  //setting connection parameters
  CONST DBHOST = "localhost";
  CONST DBUSER = "root";  //or whichever username you created
  CONST PASSWORD = ""; //password is empty by default, enter yours if you have one
  CONST DBNAME = "learning_insert";

  //setting up connection
  $conn = mysqli_connect(DBHOST, DBUSER, PASSWORD, DBNAME);

  //confirm connection
  if(mysqli_connect_errno()){

    die('Failed to connect to db'.mysqli_connect_error().'('.mysqli_connect_errno().')');
  }else {
    echo  "connection successful";
  }
  if (isset($_POST['submit'])){

        //if the submit button is pressed create variables
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $phonenumber = $_POST['number'];

$sql =  "INSERT INTO `user_info ` (firstname, lastname, phonenumber) VALUES ('{$firstname}', '{$lastname}', '{$phonenumber}')";
                       
     if($insert = mysqli_query($conn, $sql)) {
            echo "you have inserted data successfully";
            }else{
                   $echo = "data not saved".mysqli_error($conn);
                }

}

?>
</head>
<body>
    <h1>This is the sign up page</h1>
    <br><br>
    <form class="" action="index.php" method="post">
      <label for="firstname">Firstname</label>
      <input type="text" name="firstname" required placeholder="firstname"/><br><br>
      <label for="lastname">Lastname</label>
              <input type="text" name="lastname" required placeholder="lastname"/><br><br>
      <label for="email">Phone Number</label>
      <input type="text" name="number" required placeholder="enter phone number"><br><br>

      <button type="submit" name="submit">Sign up</button> <br><br>
    </form>
</body>”

….AAAND YOU’RE DONE
At this stage our database is connected to index.php. We can now test if everything is working fine.

On clicking the sign up button, you’ll see a success message

Now, let’s check our database and confirm that the information has been stored successfully.