Friday, 14 April 2017

Database Structure of Nairaland Like Forum

Hey Welcome back to continuation of Nairaland Forum Design, Here is the Nairaland.com like Forum Database Structure, this is a step-by-step tutorial to design a complete Nairaland forum system.
I have 10 tables here for now but as we grow in our development sure we will have more tables. The below ERD has explained the relation of this tables.                                         Demo

Source Code

Users Tables

--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `email` varchar(70) NOT NULL,
  `password` varchar(100) NOT NULL,
  `status` int(5) NOT NULL,
  `avater` varchar(100) NOT NULL,
  `validcode` varchar(100) NOT NULL,
  `passreset` varchar(100) NOT NULL,
  `activeSince` int(11) NOT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;

PHP Code for email confirmation and Complete Registration

Change where you see  http://www.thewallclone.com to your own domain address 

HTML Form
 You call this whatever you like

<form class="form-inline" action="do_confirm_email.php?" method="get"> 
      <div class="form-group"> <label for="exampleInputEmail2">Email</label> 
          <input type="email" name="email" SIZE="50" required class="form-control" id="exampleInputEmail2" placeholder="jane.doe@example.com"> </div>
           <button type="submit" name="invite" class="btn btn-primary">Send invitation</button> 
            <br/><small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else if you don't want to.</small>
      </form>


Let call this file do_comfirm_email.php 

<?php
/* --------------------------------------------------------------------------------------- */
  if(isset($_GET['invite'])){
  $email = $_GET['email']; //Storing email in $email variable.
  $code=md5(uniqid(true)); // random alphernumeric character store in $code variable for verification

/*   checking if user already exist     */
$match = $db->query("SELECT * FROM users WHERE email ='$email' AND status='1' AND username!='0' "); 
@$mysql_num_rows = mysqli_num_rows($match);

/*   checking if requested to join     */
$requested = $db->query("SELECT * FROM users WHERE email ='$email' AND status='0' AND username='' "); 
@$num_rows = mysqli_num_rows($requested);
$data=mysqli_fetch_array($requested);

/* --------------------------------------------------------------------------------------- */

              if($mysql_num_rows)// if already requested, send new link!'
              { 
               echo ' <div class="section-title">
                  <h1 style="color:green"><strong>Already a member!</strong></h1>
                  <div class="divider"></div>
                </div>';

              } else
/* --------------------------------------------------------------------------------------- */
// if not registered run the below script,
if (!$num_rows) 
{

//echo "$email $code";

  $db->query("INSERT INTO users (email, validcode) VALUES ('$email', '$code')");  // insert into our table users with unique random code


  /* Send a registration link to entered email address */
  $to = $email;
  $subject = "Confirm registration";
  $header = "Nairaland Demo";
  $body = "Thank you for registering with us. You are now part of a great community 
  For active your account, visit the link below to complete your registration: 
  http://www.thewallclone.com/register?email=$email&validcode=$code
    (You must complete your registration within a few days)";

  $sent=mail($to,$subject,$body,$header);

/* if email is sent display success message */
if ($sent) {

  echo ' <div class="section-title">
    <h1 style="color:green"><strong>Please Check Your E-Mail!</strong></h1>
    <p>We have just sent you an e-mail.<p>Please <b>check your inbox</b> 
    to find the e-mail and <b>complete your registration</b>.
    <p>Please <b>check your spam folder</b> if you cannot find it in your inbox. <p>Welcome to Nairaland!<p>
    <div class="divider"></div>
  </div>';
      } /* end if statement for sent */

}
  /* --------------------------UPDATE REGISTRATION LINK--------------------------------------------- */
  if ($num_rows) {
   $dbCode=$data['validcode'];
   $dbEmail=$data['email'];
  // echo "$email $dbCode";
   /* Send a registration link to entered email address */
  $to = $email;
  $subject = "Confirm registration";
  $header = "Nairaland Demo";
  $body = "Thank you for registering with us. You are now part of a great community 
  For active your account, visit the link below to complete your registration: 
  http://www.thewallclone.com/register?email=$dbEmail&validcode=$dbCode
    (You must complete your registration within a few days)";

  $sent=mail($to,$subject,$body,$header);

/* if email is sent display success message */
if ($sent) {

  echo '<div class="section-title">
    <h1 style="color:green"><strong>Link resent!</strong></h1>
    
  </div>';
      } /* end if statement for sent */
/* --------------------------------------------------------------------------------------- */
}

} /* end if get statement */
?>

And call this register.php 

after email as been confirmed the user will be redirected to this page to complete registration

<?php

 if(isset($_GET['validcode']) && ($_GET['email']) )
     {

     $code = $_GET['validcode'];
     $email = $_GET['email'];

     $match = $db->query("SELECT * FROM users WHERE email ='$email' AND validcode='$code' AND status='0' "); 
    $mysql_num_rows = mysqli_num_rows($match);
    $row=mysqli_fetch_array($match);
{
$uid=$row['uid'];
$validcode=$row['validcode'];
$email=$row['email'];


    if($mysql_num_rows)
{ 

 echo '<div class = "panel panel-default">   
   <div class = "panel-body">
      Complete Registration
   </div>
      <div class = "panel-heading">
      <form class="form-inline" action="success.php?email='.$email.'&token='.$validcode.'" method="post"> 
        <div class="form-group"> <label for="exampleInputName2">Name</label> 
        <input type="hidden" name="email" value="'.$email.'">
        <input type="text" name="username" class="form-control" id="exampleInputName2" placeholder="Jane Doe"> </div>

        <div class="form-group"> <label for="exampleInputEmail2">Password</label> 
          <input type="password" name="password" required class="form-control" id="exampleInputEmail2" placeholder=""> </div>
           <button type="submit" name="join" class="btn btn-primary">Join</button> 
      </form>
   </div>
</div>';
}

else
{
   echo ' <div class="section-title">
    <h1>An error occured!</h1>
    <div class="divider"></div>
  </div>
';
}
}
}

?>



Profile Table


--
-- Table structure for table `profile`
--
CREATE TABLE IF NOT EXISTS `profile` (
  `pid` int(11) NOT NULL AUTO_INCREMENT,
  `uid_fk` int(11) NOT NULL,
  `day` varchar(11) NOT NULL,
  `month` varchar(11) NOT NULL,
  `year` varchar(11) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `personal_text` varchar(100) NOT NULL,
  `signature` varchar(20) NOT NULL,
  `web_title` varchar(50) NOT NULL,
  `web_url` varchar(30) NOT NULL,
  `location` varchar(30) NOT NULL,
  `yim` varchar(30) NOT NULL,
  `twitter` varchar(30) NOT NULL,
  PRIMARY KEY (`pid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

Category Table


-- Table structure for table `category`
--

CREATE TABLE IF NOT EXISTS `category` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `url` varchar(50) NOT NULL,
  `des` varchar(20) NOT NULL,
  PRIMARY KEY (`cid`)
) 

Sub_category Table


--
-- Table structure for table `sub_cat`
--

CREATE TABLE IF NOT EXISTS `sub_cat` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `sname` varchar(50) NOT NULL,
  `surl` varchar(50) NOT NULL,
  `cid_fk` int(11) NOT NULL,
  PRIMARY KEY (`sid`)
)

Followed Board


--
-- Table structure for table `followed_boards`
--

CREATE TABLE IF NOT EXISTS `followed_boards` (
  `fid` int(11) NOT NULL AUTO_INCREMENT,
  `board_id_fk` int(11) NOT NULL,
  `user_id_fk` int(11) NOT NULL,
  `bdate` varchar(30) NOT NULL,
  PRIMARY KEY (`fid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

Topic Table

Topic Demo
--
-- Table structure for table `topics`
--
CREATE TABLE IF NOT EXISTS `topics` (
  `topic_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `link` varchar(100) NOT NULL,
  `content_text` text NOT NULL,
  `user_id_fk` int(11) NOT NULL,
  `board_id_fk` int(11) NOT NULL,
  `created` varchar(10) NOT NULL,
  PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ;

Topic Comment

CREATE TABLE IF NOT EXISTS `topic_comments` (
  `comment_id` int(11) NOT NULL AUTO_INCREMENT,
  `comment` text NOT NULL,
  `quote_id` int(11) NOT NULL,
  `topic_id` int(11) NOT NULL,
  `board_id_fk` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `creator` int(11) NOT NULL,
  `comment_id_fk` int(11) NOT NULL,
  `commentedOn` varchar(20) NOT NULL,
  PRIMARY KEY (`comment_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=86 ;

Followed Topic Table

--
-- Table structure for table `followed_topics`
--

CREATE TABLE IF NOT EXISTS `followed_topics` (
  `fid` int(11) NOT NULL AUTO_INCREMENT,
  `topic_id_fk` int(11) NOT NULL,
  `user_id_fk` int(11) NOT NULL,
  `fdate` varchar(30) NOT NULL,
  PRIMARY KEY (`fid`)
) 

Page View Table


--
-- Table structure for table `pageviews`
--

CREATE TABLE IF NOT EXISTS `pageviews` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `topic_id` int(11) NOT NULL,
  `views` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=28 ;

PHP Code for Total View

$page=$pid; // for example

$pageviews = $db->query("SELECT * FROM pageviews WHERE topic_id='$page'");
$total_pageviews = mysqli_num_rows($pageviews);
$row=mysqli_fetch_array($pageviews);

$views=$row['views'];
$total=$views+1;
  //echo "$total";

if ($total_pageviews) {
  # code...
$db->query("UPDATE pageviews SET views='".$total."' WHERE topic_id='$page' ");
}
else
{
$db->query("INSERT INTO pageviews (topic_id,views) values('$page','1')");
}

echo number_format($total); //display number of page views


Total View

--
-- Table structure for table `total_visitors`
--

CREATE TABLE IF NOT EXISTS `total_visitors` (
  `id` int(11) NOT NULL,
  `session` varchar(100) NOT NULL,
  `ip` varchar(50) NOT NULL,
  `status` int(11) NOT NULL,
  `time` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

That is all for now stay back enjoy and subscribe as i bring you more tutorials at codexpress creative

Tuesday, 14 March 2017

How to design login page for web application

Welcome back guys, here is custom made login template for your web app, on this tutorial am going to show you guys how to design login page, our output is simply going to look like this.


So, let start making our login page, first let create an empty file, name it login.html

Secondly add below code to our login.html file we just created earlier


<!DOCTYPE html>
<html>
<head>
 <title>Login Page</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

<div class="container">
<div class="logo">
 <img src="img/logo1.png">
</div>
 <div class="form">
  <form method="post" action="" autocomplete="">
   <p><label name="username">Username:</label>
   <input type="text" required="" name="username">
   </p>

   <p><label name="password">Password:</label>
   <input type="password" required="" name="username">
   </p>
   <p><input type="submit" value="Sign In" name="username">
   </p>
  </form>
 </div>
</div>

</body>
</html>

So, i guess is not that hard for you to ride along...
Thirdly let create all our css classes, and tag identifiers open another empty page and save it as style.css, copy below css code to it and save.

Our container class hold the content of our whole login code and that is where we defined our width: 500px; and margin-top: 200px.

Our background image could be download from  here

using css tag identifier we called up our body and set some property and attribute to make our background

 body
  {
   background-image: url(../img/bg1.jpg);
   background-size: 1400px;
  }

Then, the login button was tweaked with css to gain that nice attractive looking, below is the css code for login button, sure you can tweak it around.

input[type=submit]
  {
   width: 100px;
   border-radius:10px;
   font-size: 14px;
   font-family:cursive;
   padding-left: 10px;
   padding-top: 5px;
   padding-right: 10px;
   padding-bottom: 5px;
   background-color: #007497;
   color: #fff;
   font-weight: bold;
   cursor: pointer;
  }
  input[type=submit]:hover
  {
   
   cursor: pointer;
   background-color: #015d79;
  }

Click demo to see the final out and download for your next web app... see you yeah

Monday, 27 February 2017

Lightweight countdown timer

School days are pretty awesome, run back kicking and hailing all the these we could do, Physics and Chemistry class were taught for me but i made it all through, stop watch and countdown were used those time to determined how long reaction can take place, so far so good.
Surely get through that using javascript believe me working around js is really fun and great, every programming language has it's weak point somewhere, am going to cut it pieces providing solution, having good time with js, I bet you won't forget this day you make up your mind to try javascript, speeding that one minute is a worthwhile. if you're working on a timing project this will give you a workout. pretty sure about that. we're just going to great function in js and parse it around to get what you desire, easy right?

Download ScriptDemo

<script>
     $(document).ready(function(){

   var c = 60*60*60;
         var t;
            timedCount();
            function timedCount() {
             var hours = parseInt( c / 3600 ) % 24;
             var minutes = parseInt( c / 60 ) % 60;
             var seconds = c % 60;
             var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
             $('#timer').html(result);
                if(c == 0 ){ c = 60*60*60; }
                c = c - 1;
                t = setTimeout(function(){ timedCount() }, 1000);
            }
     });
    </script>

c = 60*60*60; the very first 60secs count for hours and second 60 sec count for minuuteand third count for secs
parse it against 24 hours, parse minut against 60 seconds. this is the workthough.

Call up $('#timer').html(result); to populate the counting figure, a function was created timedCount()

Here is the demo just in case, u wanna work it around to suit your need or download the code below.



Friday, 24 February 2017

My New Year Resolution

Hey guys how have you been all these while? I'm little bit OK for my new year resolution plan, kind of thing that i found interesting. Somehow, somewhat it all happened right? did your resolution worked for you? or did you even had one? haha. Sorry i don't wanna break rules here as part of my resolution, because life is for learning and learning for life, the difference between wrongs and right.

        Today is going to mark one of my most happiest day in my life, it's been 23 years as i give a  dam chance for Military job here in Nigeria, i have passion, love for combats, weapons, armory, jungle runs and training, i think is a time i give a thought about it, this year is super awesome for me with all this military and weapons stuff it will make a long run and a huge differences. 
So, it's 2017 again with this military stuff on my new year resolution plan, finally got the form picked and called for test into the Nigeria Airforce this is wonderful. 

Now, today been sat, 25-02-2017 is gonna make it all happen with some extra few benefit, i have been in Port harcourt, choba to be precise for few days now with a friend Governor George, I never had a sweet night since then, spending my whole night on UNIPORT School campus preparing for today test, pretty awesome right? that's what i thought as well. I'm not going to dump my programming skill these are extra few benefit to my career  i build around Military. Anyway i will be at 115 Special Operations Group, Nigerian Air Force, Port-Harcourt.  before 9:00 am in the morning.

Why Join Nigerian Airforce

This stuff really wired me out every time i give a thought, because this is the career i choose for myself all these life. I'm going to this airforce, military of a thing because i want to be, this will really gonna make me feel good and better, salary is a secondary option for me, I always wanted to know thing that makes me happy. so choose this life, me and myself with my playmate(Short Gun) riding along the beach fishing and hunting for demons on the rough side of heaven, i am that man i really want to be all these years hope you understand...

Talk is cheap, how about my parents? are they really proud of this my new year resolution, aaah that's alot to ask, pretty sure i think they do, my Dad have been hunting animals for some years and some time i go hunting with him on weekend sunrise days, this really over whelm and triggered this eagerness to join the Airforce, willingness, able and ready all the time.

I love travelling most of the time, i never had the chance to travel around country with my Dad, like going to some fishing, tourist, business trip and all that stuff never kick off.

So, if you're reading this probably i got less than 5 hours left to be there, promised to never make the mistake they made. maybe this new resolution gonna work out well. Ahh hmm never had a new year resolution before anyway. 

Friday, 27 January 2017

Pascal Program to Find Factorial of a Any Positive Number

Hey, is been a while today tutorial is on Pascal Program to Find Factorial of  Any given Positive Number, You will be able to Calculate the factorial of a number using the example i have given below.

 I'm sharing this code because it was my examination question on final year of computer Science, Heritage Polytechnic Eket Akwa Ibom State, here in Nigeria.

I have seen this question a lot of time been asked an there is no appropriate answer to it, so i wrote this lines of code in pascal to solve this long time mind troubling question.  

You will learn to calculate the factorial of a number using for loop in this example.

Therefore, This example uses nested for loop function in pascal. this pascal program generates factorial.

The factorial of a positive number n is given by:

factorial of n (n!) = 1*2*3*4....n

Example: Factorial of a Number In Pascal



program FactorialOfAnyNumber;
var
i,a,b,j:integer; {initialize variables}
begin
writeln('Enter Any number:'); { Display message for next action}
readln(j); {accept input from keyboard}

for i := 1 to j do {loop through value store in j variable}
begin
a:=i*a; {incremnet as it loop an store result in a variable}

for a:=1 to a do { loop result}
begin
  b:=a; {store total answer to to variable b}
end; {end for loop statement}
end; {end for loop statement}

  writeln('The factorial of ',j,' is = ',b); {Dispay result on screen}
readln(); {delay message}
end. { end program, terminate }

This program takes a positive integer from the user and computes factorial using for loop.

Friday, 13 January 2017

Check how many users are logged in your website using php

Total number of users  online
Total number of users  online
Hello guys, is me again with another demanded tutorial, If you are a developer, then this is very important tutorials for you, the best way to count logged in users in php, fasting your keyboard and please keep close attention in this post.




Demo Download
So, today i am going to explain how many users are logged in to your website, I will unveil the code written in php, knowing the number of users logged in your site if you are trying to know how many users are logged in to your webpage, then you don’t need to worry anymore, is really such a nice way to tells you how many people are currently using your site, best to display this somewhere on your is just ok. the script is been test on [PHP: 5.4.7] working perfect and It is the very useful.

Now, there are few things to consider:

  •  Get the ip address of current logged in user
  •  Get current timestamp
  • Get logged in username
 This will help us to list the appropriate number of users online. 

How to get client IP address in php

One way to get user IP address is $_SERVER[REMOTE_ADDR] this track the IP address from which the user is viewing the website.
$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.


$_SERVER['REMOTE_ADDR']; // Returns the IP address from where the user is viewing the current page

With the code above you would track any IP address viewing your webpage. 

PHP time(); Function

int time ( void ) Returns the current time measured in the number of seconds
time(); example
<?php
$upWeek = time() + (7 * 24 * 60 * 60);
                   // 7 days; 24 hours; 60 mins; 60 secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $upWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

The above example will output something similar to:
Now:       2017-01-13
Next Week: 2017-02-06
Next Week: 2017-02-06


The function time() returns always timestamp that is timezone independent (=UTC). Check PHP Website for more info.

How to get current timestamp


<?php
$current_time=time(); // Return the current time as a Unix timestamp
echo $current;
?>

This return the current time as a Unix timestamp
In addition to format it to a date:


<?php
$current_time =time();
echo($current_time . "<br>");
echo(date("Y-m-d",$current_time));
?>

Table structure for logged in users script


CREATE TABLE IF NOT EXISTS `total_visitors` (
  `id` int(11) NOT NULL,
  `session` varchar(100) NOT NULL,
  `ip` varchar(50) NOT NULL,
  `status` int(11) NOT NULL,
  `time` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Source code for count how many users are logged.



<?php
 $current_time=time(); // Return the current time as a Unix timestamp
 $timeout = $current_time - (120); // 2min, How long ago
 $user_ip=$_SERVER['REMOTE_ADDR']; // get user ip address

if($_SESSION)
 {
 $session_exist = $db->query("SELECT session FROM total_visitors WHERE session='".$_SESSION['username']."'");
 $session_check = mysqli_num_rows($session_exist);
 if($session_check)
 {
$sql = $db->query("UPDATE total_visitors SET time='".time()."' WHERE session='".$_SESSION['username']."' ");
 }
 else{
  $db->query("INSERT INTO total_visitors values ('','".$_SESSION['username']."','".$user_ip."','1','".$current_time."')");

 }
}
 $select_total = $db->query("SELECT * FROM total_visitors WHERE time>= '$timeout' AND status=1 ");
 $total_online_visitors = mysqli_num_rows($select_total);

 $total_online = $db->query("SELECT * FROM total_visitors WHERE time>= '$timeout' ");
 $count_visitors = mysqli_num_rows($total_online);


<p>In total there is <strong><?php echo number_format( $count_visitors); ?></strong> user online :: 
<br> <strong style="color: #098;"><?php echo number_format($total_online_visitors);?> </strong>
registered and <strong><?php echo number_format($total_online_guest);?></strong> guest <br>
<b>in last 1 minutes</b>!</p>

Demo Download
Alright, see you guys later… subscribe, share with friend…