PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: Mysql
Mysql - phponwebsites.com
Showing posts with label Mysql. Show all posts

18 Apr 2015

Create Search API like itunes Search API using PHP and MySQL

                      The Apple itunes provided a search API for retrieve app information from it. The Apple search API display result as JSON format. Do you want to know more information about Apple itunes search API, then visit iTunes Search API.

                      You can also create search API like Apple itunes search API if you know how to create JSON file using PHP. Due to this, you can provide search API for your websites. If you didn't know create JSON file using PHP and MySQL, then visit How to get output as JSON format using PHP and Mysql.

Generate Search API using PHP and MySQL


                       Lets see how to create search API using PHP.  Follow below steps to generate search API for your websites using PHP.

Step1: Connect MySQL database using PHP


                     Connect your MySQL database to get stored values from it using PHP. The PHP code for connect MySQL database is below:

 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('fitness') or die(mysql_error());


Step2: Get value from url using PHP


                     While user search something on your search API, you need to get those values for search from url. So only you can provide particular results from your MySQL database. This is done by below PHP code.

 $field=$_REQUEST['field'];
 $limit=$_REQUEST['limit'];

Step3: Make MySQL select query


                     After got values from url, you've to make MySQL query to select corresponding results from database. You can get zero or more than one values from urls for search. You should make MySQL query like below using PHP.

 if($field!='' && $limit!='')
 {
   $cond="where name='".$field."' order by id desc limit 0, $limit";
 }
 if($field=='' && $limit!='')
 {
   $cond="order by id desc limit 0, $limit";
 }
 if($field!='' && $limit=='')
 {
   $cond="where name='".$field."' order by id desc limit 0, 50";
 }
 if($field=='' && $limit=='')
 {
   $cond="order by id desc limit 0, 50";
 }
 $q=mysql_query("select * from f_img $cond") or die(mysql_error());

Step4: Add header for get output as JSON format


              You must add header type ato your PHP script for get output as JSON format. This is like below

 header('Content-Type: Application/json');

Step5: Add content to JSON file using PHP


               You need to create 2 array for create output as multidimensional array. Retrieve values from query result using mysql_fetch_arrayThen you push values to array using array_push() in PHP. Finally encode the results to display output as JSON format using json_encode().

               The full PHP code for create search API is represented below,


<?php
 error_reporting('E_ALL ^ E_NOTICE');
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('fitness') or die(mysql_error());
 $field=$_REQUEST['field'];
 $limit=$_REQUEST['limit'];
 if($field!='' && $limit!='')
 {
   $cond="where name='".$field."' order by id desc limit 0, $limit";
 }
 if($field=='' && $limit!='')
 {
   $cond="order by id desc limit 0, $limit";
 }
 if($field!='' && $limit=='')
 {
   $cond="where name='".$field."' order by id desc limit 0, 50";
 }
 if($field=='' && $limit=='')
 {
   $cond="order by id desc limit 0, 50";
 }
 $q=mysql_query("select * from user $cond") or die(mysql_error());
 header('Content-Type: Application/json');
 $details=array();
 $user=array();
 while($res=mysql_fetch_array($q))
 {
  $user['name']=$res['name'];
  $user['state']=$res['state'];
  $user['country']=$res['country'];
  array_push($details,$user);
 }
 //print_R($details);
 echo json_encode($details);

?>


           Your JSON output should be like below,


[
 {"name":"Clark","state":"California","country":"USA"},
 {"name":"Anderson","state":"Los Angeles","country":"USA"},
 {"name":"Smith","state":"London","country":"United Kingdom"},
 {"name":"Jones","state":"Cambridge","country":"United Kingdom"},
 {"name":"Nathan","state":"Franche Comte","country":"France"},
 {"name":"Marie","state":"Paris","country":"France"},
 {"name":"Nastya","state":"St Petersburg ","country":"Russia"},
 {"name":"Dima","state":"Moscow","country":"Russia"},
 {"name":"Linh","state":"Hanoi","country":"vietnam"},
 {"name":"Hoang","state":"Hai Phong","country":"vietnam"},
]

Step6 : .htaccess


                   Add following lines to your .htaccess file


RewriteRule ^search search.php [L]

                  Now you entered search on address bar, the .htaccess redirects you to search.php file. You can get search API using below url types.

                http://www.phponwebsites.com/search?field=nathan&limit=10
                http://www.phponwebsites.com/search?field=nathan
                http://www.phponwebsites.com/search?limit=10
                http://www.phponwebsites.com/search

21 Mar 2015

Retrieve images from mysql database using php

                       Already you know  how to upload images to mysql database using php. Otherwise, visit upload images to mysql database using php.

Retrieve images from database:

                        Normally you can retrieve data from mysql table using php. Then you print the result. Similarly you retrieve image name from mysql database and print image name with located folder in '<img>' tag.

Consider following mysql table.


Retrieve images from mysql database

 The php script for retrieve images from mysql database is:


<?php
        mysql_connect('localhost','root','') or die(mysql_error());
        mysql_select_db('new')  or die(mysql_error());
        $q=mysql_query("select * from image where no=1 ")  or die(mysql_error());
        $res=mysql_fetch_array($q);
?>
    <img src="<?php echo 'http://localhost/upload/image/'.$res['img_name'];?>">

   
      where,
                 mysql_query() select the row which is no '1' from mysql database.
                 mysql_fetch_array() return the result an associated array. You want to know about  mysql fetch array().
                 In your img src print image name with location of image. Now you''ll get output like this:


phponwebsites

Related Post:

30 Oct 2014

Upload images to mysql database using php

                         In this method, You won't need to store images in mysql database. Just store image name in mysql database and store image in particular directory. Then you can retrieve image from particular directory using image name in database. You can done it using php.

Create table using mysql query:


                create table image(
                     no int(4) AUTO_INCREMENT, img_name varchar(30), 
                     PRIMARY KEY(no) )
Now the table 'image' is created. Then you can store values to mysql database using php.

Upload images using php and mysql:


                  The php script for upload images to mysql database is:


<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
File: <input type="file" name="file">
       <input type="submit" name="submit" value="Upload">
</form>
<?php
 if(isset($_POST['submit']))
 { 
   mysql_connect('localhost','root','');
   mysql_select_db('new');
   $name=$_FILES['file']['name'];
   $type=$_FILES['file']['type'];
   if($type=='image/jpeg' || $type=='image/png' || $type=='image/gif' || $type=='image/pjpeg')
   {
if(file_exists(dirname($_SERVER['DOCUMENT_ROOT']).'/oops/upload/image/'.$name))
     {
      echo'file is already present';
     }
     else
     {
      $up=move_uploaded_file($_FILES['file']['tmp_name'],dirname($_SERVER['DOCUMENT_ROOT']).'/oops/upload/image/'.$name);
      $q=mysql_query("insert into image values('','".$name."')");
  if($up && $q)
  {
   echo'image uploaded and stored';
  }
  elseif(!$up) 
  {
   echo'image not uploaded';
  }
  elseif(!$q)
  {
   echo'image not stored';
  }
 }
   }
   else
   {
    echo'Invalid file type';
   }
 }
?>
</body>
</html>


        where,
                   $_FILES['file']['type'] is used to return the type of uploaded file.
                   move_uploaded_file() is used to upload the file.
You want to know about upload files in php.
                    if($type=='image/jpeg' || $type=='image/png' || $type=='image/gif' || $type=='image/pjpeg' ) is used to check the file type whether it is image or not. If it is image, then it is stored. Otherwise, it is not upload and also stored.
                   Now you can see the directory, the image is stored here and also stored in mysql database.

25 Aug 2014

Parse/Read data from XML Sitemap using PHP

                                You can Create XML Sitemap dynamically using PHP and MySQL. Then you've have a doubt. How can retrieve data from XML Sitemap using PHP? In this post, You are going to know get data from XML Sitemap using PHP.

                                 You can get value from XML Sitemap using PHP in following two ways.

1. Get data from XML Sitemap using simple_load_file() in PHP
2. Get data from XML Sitemap using file_get_contents() and SimpleXMLElement() in PHP

Lets see below examples.

Get data from XML Sitemap using simple_load_file() in PHP


                                   Simple_load_file() in PHP is used to convert XML document into an object. The below example explain retrieve data from XML Sitempa.


<?php
$xml=simplexml_load_file('http://www.phponwebsites.com/sitemap.xml');
//print_R($xml);
foreach($xml->url as $val)
 {
  echo $val->loc.' '. $val->lastmod.' '. $val->changefreq.' '. $val->priority.'<br>';
 }
?>


Get data from XML Sitemap using file_get_contents and SimpleXMLElement in PHP


                                  File_get_contents() is used to read the contents of a file into string. SimpleXMLElement is used to represents elements of XML document. The below example explain retrieve data from XML Sitemap.

<?php
$url=file_get_contents('http://www.phponwebsites.com/sitemap.xml');
$xml=new SimpleXMLElement($url);
//print_R($xml);
foreach($xml->url as $val)
 {
  echo $val->loc.' '. $val->lastmod.' '. $val->changefreq.' '. $val->priority.'<br>';
 }
?>


 When you give print_R() in above PHP file, you can see the output on screen like below.


 SimpleXMLElement Object (
   [url] => Array (
         [0] => SimpleXMLElement Object (
       [loc] => http://www.phponwebsites.com/p/php.html
           [lastmod] => 2014-07-26
       [changefreq] => daily
       [priority] => 1 )
 [1] => SimpleXMLElement Object (
       [loc] => http://www.phponwebsites.com/p/mysql.html
       [lastmod] => 2014-07-26
       [changefreq] => daily
       [priority] => 1 )
 [2] => SimpleXMLElement Object (
       [loc] => http://www.phponwebsites.com/p/htaccess.html
       [lastmod] => 2014-07-26
       [changefreq] => daily
       [priority] => 1 )
  )
)

Now you can retrieve data from XML Sitemap.

Related Post:
Create Excel file using PHP and MySQL
Create XML Sitemap dynamically using PHP and MySQL
Create RSS Feed Dynamically using PHP and MySQL
PHP : Parse data from RSS Feed using SimpleXML
Read data from JSON file using PHP
Parse data from XML file using PHP

24 Aug 2014

Create XML file using PHP and MySQL

                                   You can get output as XML format using PHP. You can import values to XML file from Mysql database using PHP.

                                   XML expands Extensible Markup Language. It is used to share your data across various platforms. You can also retrieve values from XML file using PHP.

Get output as XML format using PHP


                                    If you want to convert your Mysql table values into XML format using PHP, then follow below steps.


Step1: Add header to XML file in PHP


                                    First you need to add content type of XML file in PHP in order to get output as XML format. It need to add below PHP codes in your PHP file.

header ("content-type: text/xml");

Step2: Connect mysql database


                                    After added content type of XML, you need to connect Mysql database using PHP to retrieve values from it. You add below codes after content type in PHP file.

mysql_connect('localhost','root','');
mysql_select_db('fitness');

Step3: Add content to XML file


                                  Then select required values from Mysql database using mysql_query(). Retrieve values from query result using mysql_fetch_array. Finally your PHP file look likes below one.


<?php
header ("content-type: text/xml");
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('fitness') or die(mysql_error());
$xml='<?xml version="1.0" encoding="UTF-8"?>';
$qr=mysql_query("SELECT * FROM `f_img` order by id desc") or die(mysql_error());
$xml.='<userlist>';
while($res=mysql_fetch_array($qr))
{
 $xml.='<user><name>'.$res['name'].'</name><state>'.$res['state'].'</state><country>'.$res['country'].'</country></user>';
}
$xml.='</userlist>';
echo $xml;
?>


                                 You will get output as XML format like below,

<userlist>
    <user>
       <name>Clark</name>
       <state>California</state>
       <country>USA</country>
   </user>
   <user>
      <name>Smith</name>
      <state>London</state>
      <country>United Kingdom</country>
   </user>
   <user>
      <name>Nathan</name>
      <state>Franche Comte</state>
      <country>France</country>
   </user>
   <user>
      <name>Nastya</name>
      <state>Moscow</state>
      <country>Russia</country>
   </user>
</userlist>

                                     Now you got output as XML content. Similarly, you can get XML element's values using PHP.

Related Post:
Create Excel file using PHP and MySQL
Create XML Sitemap dynamically using PHP and MySQL
Create RSS Feed Dynamically using PHP and MySQL
PHP : Parse data from RSS Feed using SimpleXML
PHP : Parse data from XML Sitemap using simplexml_load_file and file_get_elements
Read data from JSON file using PHP
Parse data from XML file using PHP

21 Aug 2014

Create json file using PHP and MySQL

                        You can create json file using PHP and Mysql. You can get output as json format using PHP and Mysql. Before you want to know that, first you should know what is json? and what is the us of json?

JSON

      
                       JSON expands JavaScript Object Notation. It is one of the data interchange format. You can easily read and write data through JSON file.
                       It is language independent. So you can retrieve data from it using any familiar languages like PHP. It should be array format, object format and both array and object fotmat.
     The array format of Json file should be like this,

       [    
           {
              'tutorial':'PHP',
              'link':'http://www.phponwebsites.com/p/php.html'
           },
           {
              'tutorial':'Mysql',
              'link':'http://www.phponwebsites.com/p/mysql.html'
           },
           {
            'tutorial':'htaccess',
            'link':'http://www.phponwebsites.com/p/htaccess.html'
           }    
      ]

The object of JSON should be like this,

    {  
           'tutorial':'PHP',
            'link':'http://www.phponwebsites.com/p/php.html'  
    }

Get output as json format using PHP and Mysql


                           Now you know something about JSON files. So we are going to know how to get output as JSON format using php and mysql.

Add header to create json file using PHP and Mysql

       
                          If you want to create json file, then you have to add header for json file. It is like below

header('Content-Type: application/json'); 

          Where json indicate this is json file

Add content to json file using PHP


             Then you need to add contents to your json file as you want as. Retrieve values from query result using mysql_fetch_arraySuppose you have more values in a variable. Then you need to store all values in array. Consider the following PHP code.

<?php
header('Content-Type: application/json');
$linklist=array();
$link=array();
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('quicksai_quick') or die(mysql_error());
$qr=mysql_query("SELECT * FROM `links` ") or die(mysql_error());
while($res=mysql_fetch_array($qr))
{
 $link['tutorial']=$res['tutorial'];
 $link['url']=$res['url'];
 array_push($linklist,$link);
}
//print_R($linklist);
echo json_encode($linklist);
?>

      The above example explain how to create json file on multidimensional array using PHP and Mysql.
     where,
               array() - create array variable.
               array_push() - insert values into array
               json_encode() - encode the values and returns JSON representation of values
             

The above example will give output as json file. It should be like this:
      
      [
      {'tutorial':'PHP', 'link':'http://www.phponwebsites.com/p/php.html'},
      {'tutorial':'Mysql', 'link':'http://www.phponwebsites.com/p/mysql.html'},
      {'tutorial':'htaccess','link':'http://www.phponwebsites.com/p/htaccess.html'}
      ]
  

20 Aug 2014

Get/Read value from RSS Feed using PHP

                                You can generate RSS Feed using PHP and MySQL. Then you've have a doubt. How can retrieve data from RSS Feed using PHP? In this post, You are going to know get data from RSS Feed using PHP.

                                 You can get value from RSS Feed using PHP in following two ways.

1. Get data from RSS Feed using simple_load_file() in PHP
2. Get data from RSS Feed using file_get_contents() and SimpleXMLElement() in PHP

Lets see below examples.

Get data from RSS Feed using simple_load_file() in PHP


                                   Simple_load_file() in PHP is used to convert XML document into an object. The below example explain retrieve data from RSS Feed.


<?php
$xml=simplexml_load_file('http://www.phponwebsites.com/rss.xml');
//print_R($xml);
foreach($xml->channel->item as $val)
 {
  echo $val->title.' '. $val->link.'<br>';
 }
?>


Get data from RSS Feed using file_get_contents and SimpleXMLElement in PHP


                                  File_get_contents() is used to read the contents of a file into string. SimpleXMLElement is used to represents elements of XML document. The below example explain retrieve data from RSS Feed.

<?php
$url=file_get_contents('http://www.phponwebsites.com/rss.xml');
$xml=new SimpleXMLElement($url);
//print_R($xml);
foreach($xml->channel->item as $val)
 {
  echo $val->title.' '. $val->link.'<br>';
 }
?>


 When you give print_R() in above PHP file, you can see the output on screen like below.


  SimpleXMLElement Object (
   [@attributes] => Array ( [version] => 2.0 )
   [channel] => SimpleXMLElement Object (
         [title] => Phponwebsites
[link] => http://www.phponwebsites.com
[description] => Phponwebsites about php related topics like .htaccess, robots.txt, mysql, jquery, ajax, js and also php for php developers
         [language] => en-us
[item] => Array (
          [0] => SimpleXMLElement Object (
            [title] => PHP
  [link] => http://www.phponwebsites.com/p/php.html
               [description] => PHP doubts clarified at Phponwebsites
                )
         [1] => SimpleXMLElement Object (
            [title] => MySQL
           [link] => http://www.phponwebsites.com/p/mysql.html
               [description] => MySQL doubts clarified at Phponwebsites
               )
           [2] => SimpleXMLElement Object (
           [title] => htaccess
          [link] => http://www.phponwebsites.com/p/htaccess.html
              [description] => htaccess doubts clarified at Phponwebsites
               )
          )
    )
)

Now you can retrieve data from RSS Feed.

Related Post:
Create Sitemap dynamically using PHP and MySQL
Create RSS Feed dynamically using PHP and MySQL
PHP : Create json file
Create XML file using PHP and MySQL
PHP : Parse data from XML Sitemap using simplexml_load_file and file_get_elements
Read data from JSON file using PHP
Parse data from XML file using PHP

19 Aug 2014

Create RSS Feed dynamically using PHP and MySQL

                                    You can create RSS feed dynamically using PHP like how you create sitemap dynamically using PHP and MySQL. Before you are going to know create RSS Feed, you should know what is RSS Feed? and why you need to add RSS Feed to your websites?

What is RSS Feed?


                                   RSS expands Really Simple Syndication. It is developed in XML like Sitemap. It is like content delivery vehicle. That means, you created a product, Ii distributes it to all places. Due to this feed, the viewers of your websites can easily find the latest pages of your websites. So there is no need to spend more time to search their desired topics on your web contents. This is the short description about RSS Feed. 

For more details, visit
    RSS Feed in W3schools
    RSS Feed at rss.softwaregarden
    what is RSS Feed
    Definition of RSS Feed at press-feed

Structure of RSS Feed

             
                                   The structure of RSS Feed is described below.


<?xml version='1.0' encoding='UTF-8'?>
<rss version='2.0'>
<channel>
    <title>Phponwebsites</title>
    <link>http://www.phponwebsites.com</link>
    <description>Phponwebsites about php related topics like .htaccess, robots.txt, mysql, jquery, ajax, js and also php for php developers</description>
    <language>en-us</language>
    <item>
      <title>PHP</title>
      <link>http://www.phponwebsites.com/p/php.html</link>
      <description>PHP doubts clarified at Phponwebsites</description>
   </item>
  <item>
      <title>MySQL</title>
      <link>http://www.phponwebsites.com/p/mysql.html</link>
      <description>MySQL doubts clarified at Phponwebsites</description>
   </item>
  <item>
      <title>htaccess</title>
      <link>http://www.phponwebsites.com/p/htaccess.html</link>
      <description>Htaccess doubts clarified at Phponwebsites</description>
   </item>
</channel>
</rss>

Generate RSS Feed dynamically using PHP and MySQL


                 Let see how to create RSS Feed dynamically using PHP and MySQL. Follow the below steps to create feed.


1. Create database and table


                  First you create database for store your link details on it. The below MySQL query is used for create database.

                Create database new

 where new is database name

                Use new

The above query is used to use database "new".
                  The MySQL query for create table is,

                Create table links (id int not null auto_increment primary key, name varchar(200), link varchar(200), description varchar(250))

                 Now the table "links" is created. Then store values into table using below query

                insert into table links values('','PHP','http://www.phponwebsites.com/p/php.html','PHP doubts are clarified at Phponwebsites')

                After insert values into table, your table look likes below

insert values into MySQL table for RSS Feed


2. Add header type RSS Feed


                            First you need to add content type of RSS feed. It is represented below.

header("Content-Type: application/rss+xml; charset=ISO-8859-1");


3. Add content to RSS Feed

                         
                            First of all you need to store all links in your database. Then on;y you can retrieve it using PHP. The below example we Retrieve data from MySQL database using mysql_fetch_array in PHP.
After added header, you have to add some name spaces for RSS Feed. Finally add contents to RSS Feed.


<?php
header("Content-Type: application/rss+xml; charset=ISO-8859-1");
echo '<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?>
<?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?>
<rss
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
    xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0"
version="2.0">
<channel>
<title>Phponwebsites</title>
<link>http://www.phponwebsites.com</link>
<description>Phponwebsites about php related topics like .htaccess, robots.txt, mysql, jquery, ajax, js and also php for php developers</description>';
       $connection = @mysql_connect('localhost', 'root', '') or die(mysql_error());
       mysql_select_db('new')  or die (mysql_error());
       $query = "SELECT * FROM links order by id desc";
       $rss = mysql_query($query) or die (mysql_error());
       $ImgPath='http://2.bp.blogspot.com/-vwl4cGyoDPM/UqKklyTGE-I/AAAAAAAAALI/iOipE7-PhAM/s1600/logo5.png';
       while($row=mysql_fetch_array($rss)){
       echo '
<item>
<title>'.$row['name'].'</title>
<link>'.$row['link'].'</link>
<content:encoded>
      <![CDATA[<p align="left">
          <a href="'.$row['link'].'"><img style="background-image: none; " border="0" src="'.$ImgPath.'" />    </a></p>]]>
       </content:encoded>
       <description>'.$row['description'].'</description></item>';
}
      echo '</channel>
</rss>';
?>

               When you run this file on firfox, you will get output like below

Create RSS Feed dynamicall using PHP and MySQL


4. Htaccess


                         Then you have to add below lines to your htaccess file.


                    RewriteRule ^rss.xml$ rss.php [L]

When you type rss.xml in your browser address bar, it redirects to rss.php.

             Finally you got dynamic RSS Feed.

Related Post:
Read data from RSS Feed using PHP
Create json file using PHP and MySQL
Create XML file using PHP and MySQL
PHP : Parse data from XML Sitemap using simplexml_load_file and file_get_elements
Read data from JSON file using PHP
Parse data from XML file using PHP

29 Jul 2014

Generate Yearly Statistics dynamically using PHP and MySQL

                       All of you know to create daily statistics and also monthly statistics using php and mysql. You can also create yearly statistics using php and mysql. The php and mysql allows user to create charts on daily, monthly and yearly charts between two years. Due to this yearly stats, you can find how much your website got viewed and also find comparison of number of visits.

Yearly stats using php and mysql:


                      You need to follow the below steps to create yearly stats using php.

1.Create table in mysql database:


             First you have to create table for update values.

                  Create table stats(view int(10),date date)

          Now the table is created with fields view and date.

2.Counter code in php:

   
                  Then you add the number of views to mysql table using php. Add the following code to header of each page in your website. Because header is in all pages. So you can easily calculate the number of views of your website. Due to this code, you can find total number views of your website per day.


<?php
    mysql_connect('localhost','root','')  or die(mysql_error());
    mysql_select_db('new')  or die(mysql_error());
    $q=mysql_query('select * from stats where date IN (CURDATE())')  or die(mysql_error());
    $n=mysql_num_rows($q);
    if($n==0)
    {
     mysql_query("insert into stats values(1,CURDATE())");
    }
    else
    {
     mysql_query("update stats set view=view+1 where date IN (CURDATE())");
    }
?>

where,
      - select * from stats where date IN (CURDATE()) is select the views if present in current date.
      - mysql_num_rows() return the number of rows selected. If it is 0, then value inserted into mysql table. Otherwise values are updated.

3. Stats(chart) using php and mysql:


                    Then you need to create statistics using php and mysql through google charts. There are many types of charts in google. You can choose anything as you want. The php code for create yearly stats:

yearly_stats.php



<html>
<body>
<?php
    mysql_connect('localhost','root','');
    mysql_select_db('new');
?>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {var data = google.visualization.arrayToDataTable([
  <?php
$str=" ['Year', 'Year'] ";
$query="select SUM(view) as vi, DATE_FORMAT( date, '%Y' ) as dat from stats group by DATE_FORMAT(date, '%Y') order by DATE_FORMAT(date, '%Y') "; 
$result=mysql_query($query);
while($rows=mysql_fetch_array($result,MYSQL_BOTH)){
$str =$str . ",['". $rows['dat'] ."'," .$rows['vi'] ."]" ;
}
echo $str;
?>
        ]);

      var options = {
          //title: 'Company Performance',
          hAxis: {title: 'Year', titleTextStyle: {color: 'red'}},
          vAxis: {title: 'Total views', titleTextStyle: {color: '#FF0000'}, maxValue:'5', minValue:'1'},
        };

        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>    
   <p style="font-size:20px;">Monthly Stats</p>
   <div id="chart_div" style="width: 400px; height: 200px;"></div>
</body>
</html>

where,
          The following MySQL query is used to find total number of views of your websites per yearly.
        - select SUM(view) as vi, DATE_FORMAT( date, '%Y' ) as dat from stats group by DATE_FORMAT(date, '%Y') order by DATE_FORMAT(date, '%Y') ASC
is select the number of views monthly.

Consider the following example:
    Suppose your table look like this:

Create yearly stats dynamically using PHP and MySQL


Then you'll get output like below:

Create yearly stats dynamically using PHP and MySQL


        Now you can calculate the number of views of your website yearlly.

Related Post:
Create daily statistics using PHP and MySQL
Calculate monthly statistics dynamically using PHP and MySQL

28 Jul 2014

Monthly statistics using php and mysql

                       All of you know to create daily stats using php and mysql. Otherwise visit How to calculate daily statistics using PHP and MySQL. You can also create monthly statistics using php and mysql. The php and mysql allows user to create charts on daily, monthly and charts between two dates.

Monthly stats using php and mysql:


                      You need to follow the below steps to create monthly stats using php.

1.Create table in mysql database:


             First you have to create table for update values.

                  Create table stats(view int(10),date date)

          Now the table is created with fields view and date.

2.Counter code in php:

     
                  Then you add the number of views to mysql table using php. Add the following code to header of each page in your website. Because header is in all pages. So you can easily calculate the number of views of your website.


<?php
    mysql_connect('localhost','root','')  or die(mysql_error());
    mysql_select_db('new')  or die(mysql_error());
    $q=mysql_query('select * from stats where date IN (CURDATE())')  or die(mysql_error());
    $n=mysql_num_rows($q);
    if($n==0)
    {
     mysql_query("insert into stats values(1,CURDATE())");
    }
    else
    {
     mysql_query("update stats set view=view+1 where date IN (CURDATE())");
    }
?>

where,
           
      - select * from stats where date IN (CURDATE()) is select the views if present in current date.
      - mysql_num_rows() return the number of rows selected. If it is 0, then value inserted into mysql table. Otherwise values are updated.

3. Stats(chart) using php and mysql:


                    Then you need to create statistics using php and mysql through google charts. There are many types of charts in google. You can choose anything as you want. The php code for create monthly stats:

monthly_stats.php



<html>
<body>
<?php
    mysql_connect('localhost','root','');
    mysql_select_db('new');
?>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {var data = google.visualization.arrayToDataTable([
  <?php
$str=" ['Month', 'Month'] ";
$query="select SUM(view) as vi, DATE_FORMAT( date, '%M' ) as dat from stats group by DATE_FORMAT(date, '%Y-%M') order by DATE_FORMAT(date, '%Y-%M') ASC"; 
$result=mysql_query($query);
while($rows=mysql_fetch_array($result,MYSQL_BOTH)){
$str =$str . ",['". $rows['dat'] ."'," .$rows['vi'] ."]" ;
}
echo $str;
?>
        ]);

      var options = {
          //title: 'Company Performance',
          hAxis: {title: 'Month', titleTextStyle: {color: 'red'}},
          vAxis: {title: 'Total views', titleTextStyle: {color: '#FF0000'}, maxValue:'5', minValue:'1'},
        };

        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>      
   <p style="font-size:20px;">Monthly Stats</p>
   <div id="chart_div" style="width: 400px; height: 200px;"></div>
</body>
</html>

where,  
             The following MySQL query is used to find total number of views of your websites per monthly
        - select SUM(view) as vi, DATE_FORMAT( date, '%M' ) as dat from stats group by DATE_FORMAT(date, '%Y-%M') order by DATE_FORMAT(date, '%Y-%M') ASC
is select the number of views monthly.

Consider the following example:
    Suppose your table look like this:

Monthly statistics using php and mysql


Then you'll get output like below:

Monthly stats using php and mysql

        Now you can calculate the number of views of your website monthly.

Related Post:
Create daily statistics using PHP and MySQL
Create yearly statistics dynamically using PHP and MySQL

27 Jul 2014

Daily statistics using php and mysql

                       All website owners wants to know how many times the site is viewed ?. So they create this details in admin panel of their website. You can create daily statistics using php and mysql. The php and mysql allows user to create charts on daily, monthly and charts between two dates.

Daily stats using php and mysql:


                      You need to follow the below steps to create daily stats using php.

1.Create table in mysql database:


             First you have to create table for update values.

                  Create table stats(view int(10),date date)

          Now the table is created with fields view and date.

2.Counter code in php:


            Then you add the number of views to mysql table using php. Add the following code to header of each page in your website. Because header is in all pages. So you can easily calculate the number of views of your website.


<?php
    mysql_connect('localhost','root','') or die(mysql_error());
    mysql_select_db('new')  or die(mysql_error()); 
    $q=mysql_query('select * from stats where date IN (CURDATE())')  or die(mysql_error());
    $n=mysql_num_rows($q);
    if($n==0)
    {
     mysql_query("insert into stats values(1,CURDATE())");
    }
    else
    {
     mysql_query("update stats set view=view+1 where date IN (CURDATE())");
    }
?>


where,
      - select * from stats where date IN (CURDATE()) is select the views if present in current date.
      - mysql_num_rows() return the number of rows selected. If it is 0, then value inserted into mysql table. Otherwise values are updated.

3. Stats(chart) using php and mysql:


                    Then you need to create statistics using php and mysql through google charts. There are many types of charts in google. You can choose anything as you want. The php code for create stats:

daily_stats.php


<html>
<body>
<?php
    mysql_connect('localhost','root','')  or die(mysql_error());
    mysql_select_db('new') or die(mysql_error());
?>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {var data = google.visualization.arrayToDataTable([
 <?php
$str=" ['Day', 'Day'] ";
$query="select view as vi, DATE_FORMAT( date, '%b-%d' ) as dat from stats order by date ASC";
$result=mysql_query($query)  or die(mysql_error());
while($rows=mysql_fetch_array($result,MYSQL_BOTH)){
$str =$str . ",['". $rows['dat'] ."'," .$rows['vi'] ."]" ;
}
echo $str;
?>
        ]);

      var options = {
          //title: 'Company Performance',
          hAxis: {title: 'Day', titleTextStyle: {color: 'red'}},
          vAxis: {title: 'Total views', titleTextStyle: {color: '#FF0000'}, maxValue:'5', minValue:'1'},
        };

        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>        
   <p style="font-size:20px;">Dialy Stats</p>
   <div id="chart_div" style="width: 400px; height: 200px;"></div>
</body>
</html>

where,    
               The following MySQL query is used to find total number of views of your websites per daily
        - select view as vi, DATE_FORMAT( date, '%b-%d' ) as dat from stats order by date ASC
is select the number of views daily.

Consider the following example:
    Suppose your table look like this:

Daily stats using php and mysql


Then you'll get output like below:

Dialy statistics using php and mysql

        Now you can calculate the number of views of your website.

Related Post:
Create monthly statistics using PHP and MySQL
Create yearly statistics dynamically using PHP and MySQL 

22 Jul 2014

Create Registration / Sign up form using PHP and Mysql

                                If you want to add login form to your websites, then you need to add sign up  or registration form in order to get values from user and store it into Mysql database. Your registration form should be made in HTML and the values are stored in Mysql using PHP. Lets see create the registration form in PHP , Mysql, HTML.

1. Create Database


                               First you need to create database to store user values. You need to use below Mysql query to create database in your phpmyadmin.

            Create database db_name

     ie,
             Create database new

where new is my database name

                               Then you've to use below Mysql query for use created database.
         
             Use db_name
   
    ie,

             Use new


2. Create table in Mysql database


                               After created database, you need to create table for store users values. You can create table using below Mysql query.

             create table login (name varchar(30),password varchar(30),mail varchar(50))

                              Now  you can see created table is presented in your database.

3. Create registration form in HTML


                              After finished database and table creation, you need to create front end design which can be viewed by users. ie, client side script. Using below HTML code to create registration form in HTML.

<form action="#" method="post">
      <table id="tbl" align="center">
       <tr><td>Name:</td><td><input type="text" name="name" id="name"></td></tr>
       <tr><td>Password:</td><td><input type="text" name="password" id="password"></td></tr>
  <tr><td>Email:</td><td><input type="text" name="mail" id="mail"></td></tr>
       <tr><td></td><td><input type="submit" name="submit" id="submit" value="Submit"></td></tr>
      </table>

     </form>

4. Add styles to registration form


                            After created form in HTML, it should not be present user attractable one. So you need to add CSS styles to HTML form in order to make form colorful. Just add below CSS codes to your html form.

 body {
 color:white;
 font-size:14px;
 }
 .contact {
    text-align:center;
    background: none repeat scroll 0% 0% #8FBF73;
    padding: 20px 10px;
    box-shadow: 1px 2px 1px #8FBF73;
    border-radius: 10px;
width:520px;
 }
 #name, #password, #mail {
    width: 250px;
    margin-bottom: 15px;
    background: none repeat scroll 0% 0% #AFCF9C;
    border: 1px solid #91B57C;
    height: 30px;
    color: #808080;
    border-radius: 8px;
    box-shadow: 1px 2px 3px;
}
#submit
{
    background:none repeat scroll 0% 0% #8FCB73;
    display: inline-block;
    padding: 5px 10px;
    line-height: 1.05em;
box-shadow: 1px 2px 3px #8FCB73;
    border-radius: 8px;
    border: 1px solid #8FCB73;
    text-decoration: none;
    opacity: 0.9;
    cursor: pointer;
color:white;
}
#er {
    color: #F00;
    text-align: center;
    margin: 10px 0px;
    font-size: 17px;

}


5. Form validation in javascript


                                 After add CSS to your form, you've to validate your form using javascript or jquery.  You can validate empty textbox, validate valid email id and valid phone number using below javascript. Add below javascript validation to your HTML form.

$(document).ready(function() {
$('#submit').click(function() {
var name=document.getElementById('name').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var chk = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(name=='')
{
 $('#er').html('Enter your name');
 return false;
}
if(password=='')
{
 $('#er').html('Enter your password');
 return false;
}
if(mail=='')
{
 $('#er').html('Enter your mail');
 return false;
}
if(!chk.test(mail))
{
 $('#er').html('Enter valid email');
 return false;
}
});

});


6. Connect Mysql database using PHP


                                     Then you need to write server side script to store values into database. First you make connection to Mysql database to store user values using PHP. Visit How to connect Mysql database using PHP. Add below PHP codes

  mysql_connect('localhost','root','') or die(mysql_error());
  mysql_select_db('new') or die(mysql_error());


7. Add PHP code for store values into database


                                     Here is the PHP code for insert user data into Mysql database. This is the code for avoid duplicate entries in table. visit How to avoid duplicate values storing in Mysql table while inserting using PHP

  $name=$_POST['name'];
  $password=$_POST['password'];
  $mail=$_POST['mail'];
  $q=mysql_query("select * from login where name='".$name."' or mail='".$mail."' ") or die(mysql_error());
  $n=mysql_fetch_row($q);
  if($n>0)
  {
   $er='The username name '.$name.' or mail '.$mail.' is already present in our database';
  }
  else
  {
   $insert=mysql_query("insert into login values('".$name."','".$password."','".$mail."')") or die(mysql_error());
   if($insert)
   {
    $er='Values are registered successfully';
   }
   else
   {
    $er='Values are not registered';
   }

  }

8. PHP script for register values into Mysql database


                                        Now you combine all above codes to single PHP file. Then you'll get code like below one. visit How to insert values into Mysql database using PHP.

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style type="text/css">
 body {
 color:white;
 font-size:14px;
 }
 .contact {
    text-align:center;
    background: none repeat scroll 0% 0% #8FBF73;
    padding: 20px 10px;
    box-shadow: 1px 2px 1px #8FBF73;
    border-radius: 10px;
width:520px;
 }
 #name, #password, #mail {
    width: 250px;
    margin-bottom: 15px;
    background: none repeat scroll 0% 0% #AFCF9C;
    border: 1px solid #91B57C;
    height: 30px;
    color: #808080;
    border-radius: 8px;
    box-shadow: 1px 2px 3px;
}
#submit
{
    background:none repeat scroll 0% 0% #8FCB73;
    display: inline-block;
    padding: 5px 10px;
    line-height: 1.05em;
box-shadow: 1px 2px 3px #8FCB73;
    border-radius: 8px;
    border: 1px solid #8FCB73;
    text-decoration: none;
    opacity: 0.9;
    cursor: pointer;
color:white;
}
#er {
    color: #F00;
    text-align: center;
    margin: 10px 0px;
    font-size: 17px;
}
</style>
</head>
<body>
<?php
 error_reporting('E_ALL ^ E_NOTICE');
 if(isset($_POST['submit']))
 {
  mysql_connect('localhost','root','') or die(mysql_error());
  mysql_select_db('new') or die(mysql_error());
  $name=$_POST['name'];
  $password=$_POST['password'];
  $mail=$_POST['mail'];
  $q=mysql_query("select * from login where name='".$name."' or mail='".$mail."' ") or die(mysql_error());
  $n=mysql_fetch_row($q);
  if($n>0)
  {
   $er='The username name '.$name.' or mail '.$mail.' is already present in our database';
  }
  else
  {
   $insert=mysql_query("insert into login values('".$name."','".$password."','".$mail."')") or die(mysql_error());
   if($insert)
   {
    $er='Values are registered successfully';
   }
   else
   {
    $er='Values are not registered';
   }
  }
 }
?>
<div class="contact">
<h1>Registration Form</h1>
     <div id="er"><?php echo $er; ?></div>
     <form action="#" method="post">
      <table id="tbl" align="center">
       <tr><td>Name:</td><td><input type="text" name="name" id="name"></td></tr>
       <tr><td>Password:</td><td><input type="text" name="password" id="password"></td></tr>
  <tr><td>Email:</td><td><input type="text" name="mail" id="mail"></td></tr>
       <tr><td></td><td><input type="submit" name="submit" id="submit" value="Submit"></td></tr>
      </table>
     </form>
</div>

<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var name=document.getElementById('name').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var chk = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(name=='')
{
 $('#er').html('Enter your name');
 return false;
}
if(password=='')
{
 $('#er').html('Enter your password');
 return false;
}
if(mail=='')
{
 $('#er').html('Enter your mail');
 return false;
}
if(!chk.test(mail))
{
 $('#er').html('Enter valid email');
 return false;
}
});
});
</script>
</body>

</html>

                            When you run this file, your screen should be like this:


Create sign up form using PHP and Mysql



                  For example, you'll try to store values guru, guru, guruparthiban19@gmail.com, then your screen like below:

Insert values into Mysql database using PHP


             After enter submit button, the values are registered in Mysql database. Now you can see the values are present in yout table.





Mysql login table


               You will get error message when you tried to insert same values again. This is below

Duplicate entry error message while inserting using PHP and Mysql


                   Now your table contains user details. So you can add login form to validation user name and password of users.

Related Post:
Login form validation using PHP and Mysql
Login form validation with remeber me function using PHP and Mysql
Send forgot password to mailin login form using PHP and Mysql