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

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:

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'}
      ]
  

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

15 Jul 2014

Create excel spreadsheet using PHP and Mysql

                       You can generate excel spreadsheets easily using PHP. You need to follow below steps to create excel file.

Add content type:


                    First you need to add excel sheet content type to create excel file using PHP.

header("Content-Type: application/vnd.ms-excel");

Add name and download excel file:


                    You can provide name for excel spreadsheet and make your sheet as downloadable file on coding. The Content-Disposition is used to force browser to save a file. For that, your file should be attached following line:

header("Content-disposition: attachment; filename=spreadsheet.xls");

Add content to excel spreadsheet:


                   Finally you can add contents to your excel file. Consider the following PHP script for generate excel file:

<?php
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=spreadsheet.xls");
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('new') or die(mysql_error());
$q=mysql_query("select * from table1")  or die(mysql_error());
if(mysql_num_rows($q)>0)
{
echo"<table><tr><th>Name</th><th>Address</th><th>Phone</th></tr>";
 while($res=mysql_fetch_array($q))
 {
  echo"<tr><td>".$res['name']."</td><td>".$res['address']."</td><td>".$res['phone']."</td></tr>";
 }
echo"</table>";
}
?>

     Where,
                 mysql_fetch_array() return values as both an associative and numeric array.
                      while executing file, it required you to save excel file. After save file, you can view it. Now you got excel spreadsheet with named spreadsheet.xls which is created by PHP.

Related Post:
How to fetch result from mysql table using mysql_fetch_array in PHP
Create json 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

7 Jul 2014

Validate login form with remember me using php and mysql

                      All of you know the simple login validation concepts in php. Otherwise visit login validation using php. Now see about login form with remember me concept in php. You can remember the user using cookies concept in php.
                     When you click the remember me check box, your name and password is stored in cookie. Though you signout and close the browser, you can login again while open page in browser. Your name kept by cookie until expire the time or you clear the cache in your browser.

Remember me in login form using php:


                     Consider the following example. You have 3 php pages such as login.php, welcome.php and signout.php.

login.php:


<html>
<head>
<style type="text/css">
 input{
 border:1px solid olive;
 border-radius:5px;
 }
 h1{
  color:darkgreen;
  font-size:22px;
  text-align:center;
 }
span{
  color:lightgreen;

 }
</style>
</head>
<body>
<h1>Login<h1>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>User name:</td><td><input type='text' name='name'/></td></tr>
<tr><td>Password:</td><td><input type='password' name='pwd'/></td></tr>
<tr><td></td><td><input type='checkbox' name='remember' /> <span>Remember me</span></td></tr>
<tr><td></td><td><input type='submit' name='submit' value='Submit'/></td></tr>
</table>

</form>
<?php
session_start();
//your values are stored in cookies, then you can login without validate
if(isset($_COOKIE['name']) && isset($_COOKIE['pwd']))
{
    header('location:welcome.php');
}
// login validation in php
if(isset($_POST['submit']))
{
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('new') or die(mysql_error());
 $name=$_POST['name'];
 $pwd=$_POST['pwd'];
 if($name!=''&&$pwd!='')
 {
   $query=mysql_query("select * from login where name='".$name."' and password='".$pwd."' ");
   $res=mysql_fetch_row($query);
   if($res)
   {
    if(isset($_POST['remember']))
{
 setcookie('name',$name, time() + (60*60*24*1));
 setcookie('pwd',$pwd, time() + (60*60*24*1));
}
    $_SESSION['name']=$name;
    header('location:welcome.php');
   }
   else
   {
    echo'You entered username or password is incorrect';
   }
 }
 else
 {
  echo'Enter both username and password';
 }
}
?>
</body>
</html>

             where,
            if(isset($_COOKIE['name']) && isset($_COOKIE['pwd'])) {} means if the user values in  cookies, then the user can login directly without login validation in php.
         
           if(isset($_POST['remember'])){
           setcookie('name',$name,time() + (60*60*24*1));
           setcookie('pwd',$pwd,time() + (60*60*24*1));
           }
           which means, if the user click the remember me check box, then you have to store them in cookie. If you don't know  about cookies in php, then visit Cookies in php.

          When you run the login.php fille, you'll get output like this:

validate remember me concept in login form using php

welcome.php:


<?php    
  session_start();
  if(isset($_COOKIE['name']))
  {
    echo 'Welcome: '. $_COOKIE['name'].'<br>';
  }
  else
  {
    echo 'Welcome: '. $_SESSION['name'].'<br>';
  }
  echo'<a href="signout.php">Singout</a>';
?>

      where,
                  if(isset($_COOKIE['name'])){}else{} means if the values in cookie, then return name from cookie. Otherwise name return from session.
             Now you enter username and password  'guru' and 'guru' without select the remember check box, you will navigate to 'welcome.php' page and get output like this:

                   welcome: guru
                   Signout

 If it is wrong, then you can't login.

   

Signout in php:           


            When you click the signout.php, it destroy the session and return back to login page. The php script for signout page:
signout.php:

<?php    
         session_start();
         session_destroy();
         header('location:login.php');
?>

           You select the remember me check box while login. Then you navigate to welcome.php page. Now you click the signout on welcome.php page, you can't return back to login page. Because the concept is, when you signout the page, you return back to login.php page, where you wrote the php script as like as:
          
                  if(isset($_COOKIE['name']) && isset($_COOKIE['pwd'])) {}

It means, if values in cookie, you can login again. Now you comes to login page and again login and navigates to welcome page because your values in cookies.So you are in welcome page until the cookie is expired.

Related Post:
Create Registration form using PHP and MySQL
Simple login form validation using php and mysql
Forgot password to mail in login form validation using PHP and Mysql

2 Jul 2014

Create sitemap dynamically using PHP and MySQL

                         Do you know why you need to add sitemap into you websites? what is the use of sitemap? Let see here to solve all of your doubts about sitemap.

Sitemap:


                         Sitemap is very important for all websites. All of you know, the search engines like google, bing are crawling pages on your websites to know about websites. Using this sitemap, webmasters to inform search engines about pages for crawling. Sitemap is a XML file which contains all url of your websites upto to date. If you add new page to your site, then you'll add url of new page to sitemap for crawling.

                          Sitemap is also provide url structure of websites. Suppose a new user comes to your websites. The sitemap leads new user to all pages on your site.

Structure of sitemap: 


                    The structure of sitemap is:

<?xml version="1.0" encoding="UTF-8">
 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc>http://www.phponwebsites.com</loc>
<lastmod>today date<lastmod>
<changefreq>daily</changefreq>
<priority>1</priority>
  </url>
  <url>
    <loc>http://www.phponwebsites.com/p/htaccess.html</loc>
<lastmod>today date<lastmod>
<changefreq>daily</changefreq>
<priority>1</priority>
  </url>
 </urlset>

  where,
      urlset - encapsulates the file ie, start sitemap
      url - parent tag for each entry ie, each page
      loc - location of url
      lastmod - date for last modification of file
      changefreq -  how frequently the pag is changed. It should be always, hourly, daily, monthly, weekly, yearly, never
      priority - priority of url. It should be between 0.0 to 1.0

Create sitemap dynamically using PHP and MySQL:


                          First you need to add content type for xml to generate sitemap in PHP. ie,

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


                        Then add contents to XML file. Then save this file as sitemap.php .


<?php
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('new') or die(mysql_error());
 $dat=date('Y-m-d');
 header ("content-type: text/xml");
 echo '<?xml version="1.0" encoding="UTF-8"?>
 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
 $urls=mysql_query("select * from url")or die(mysql_error());
 while($row_Tags=mysql_fetch_array($urls))
 {
   echo "<url><loc>".$row_Tags['url']."</loc><lastmod>".$dat."</lastmod><changefreq>daily</changefreq><priority>1</priority></url>";
 }
  echo "</urlset>";
 ?>


.htaccess:

               
               In your .htaccess, you add following codes.

RewriteRule ^sitemap.xml sitemap.php [L]

                   When you run sitemap.xml on your website each time,  it display upto date contents.

Related Post:

14 May 2014

Pagination using php and mysql with jquery and ajax

                      You can display values with pagination using php. But you have to pass the page number and also relevant values through url. So your url look like this:

                                   pagination.php?p=2

                      The good php website should be contain good url strucutre. Thats why you alter the urls using .htaccess. You don't need to show passing values in url. It can be hidden by .htaccess. If you don't know, just visit Redirect urls using htaccess
                      So you need ajax and jquery to pass the values. Already you know the basic pagination concept. Otherwise, please visit Pagination using php and mysql


 Pagination using juery and ajax:


                       You need small function which is called by onclick event to display values with pagination in php. The jquery function as follows as:

<script type="text/javascript">
   function page(e) {
         $.ajax({
                       url:'pagination.php',
                       data:{p:e},
                       dataType:'html',
                       Type:'post',
                       success:function(e) {
                          $('#page').html(e);
                           }
                      });
                  }
</script>
   
         Where,
                     - function page(e){} is called from click event.
        ie, <a onclick="return page('.$i.')">'.$i.'</a>            
                    
                     - e is a page number passed from click event.
                     - pagination.php is name of this php file.
                      You define the url, data, dataType and type in ajax post to pass the values.


The overall php script for pagination: 


<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id='page'>
<?php
error_reporting('E_ALL ^ E_NOTICE');
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('new') or die(mysql_error());
$page=$_REQUEST['p'];
$limit=10;
if($page=='')
{
 $page=1;
 $start=0;
}
else
{
 $start=$limit*($page-1);
}
$query=mysql_query("select * from table1 limit $start, $limit") or die(mysql_error());
$tot=mysql_query("select * from table1") or die(mysql_error());
$total=mysql_num_rows($tot);
$num_page=ceil($total/$limit);
echo'<table><th>Reg.Id</th><th>Name</th><th>Category</th>';
while($res=mysql_fetch_array($query))
{
  echo'<tr><td>'.$res['game_ID'].'</td><td>'.$res['game_Title'].'</td><td>'.$res['category_Name'].'</td></tr>';
}
echo'</table>';
function pagination($page,$num_page)
{
  echo'<ul style="list-style-type:none;">';
  for($i=1;$i<=$num_page;$i++)
  {
      if($i==$page)
      {
         echo'<li style="float:left;padding:3px;">'.$i.'</li>';
      }
        else
     {
       echo'<li style="float:left;margin-                 left:4px;background:rgb(170,177,35);padding:4px;cursor:pointer;border:1px solid darkgreen ;"><a  onclick="return page('.$i.')">'.$i.'</a></li>';
      }
   }
  echo'</ul>';
}
if($num_page>1)
{
 pagination($page,$num_page);
}
?>
<script type="text/javascript">
function page(e) {
$.ajax({
url:'pagination.php',
data:{p:e},
dataType:'html',
Type:'post',
success:function(e){
   $('#page').html(e);
  }
});
}
</script>
</div>
</body>

</html>


You'll get output like like this:

pagination using php and jquery with ajax

                     Now you can paginated to next page. The url structure of your website should be fine.

Note:
             For pagination, you need any jquery reference like:
" <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> "

Related Post: