Thursday, December 27, 2018

CRUD Codeigniter

Blog_controller class


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Blog_controller extends CI_Controller
{
    public function index()
    {
        $this->load->model('Blog_model');
        $data['blogs_result'] = $this->Blog_model->getBlogData();
        //print_r($data);
        $this->load->view('layout/header');
        $this->load->view('Blog/blog_view', $data);
        $this->load->view('layout/footer');
    }

    public function add()
    {
        $this->load->model('Blog_model');
        $data['blogs_result'] = $this->Blog_model->getBlogData();
   
        $this->load->view('layout/header');
        $this->load->view('Blog/add_view', $data);
        $this->load->view('layout/footer');
    }

    public function submit()
    {   
        $this->load->model('Blog_model');
        $result = $this->Blog_model->saveBlogData();
        if($result)
            $this->session->set_flashdata('success_msg', 'Record Inserted.');
        else
            $this->session->set_flashdata('error_msg', 'Error.');
        redirect("index.php/Blog_controller/index");
    }

    public function edit($id)
    {   
        $this->load->model('Blog_model');
        $data2['blogs_result'] = $this->Blog_model->getBlogDatabyID($id);

        $this->load->view('layout/header');
        $this->load->view('Blog/edit_view', $data2);
        $this->load->view('layout/footer');

        // if($result)
        //     $this->session->set_flashdata('success_msg', 'Record Inserted.');
        // else
        //     $this->session->set_flashdata('error_msg', 'Error.');
        // redirect("index.php/Blog_controller/index");
    }


    public function delete($id)
    {   
        $this->load->model('Blog_model');
        $result = $this->Blog_model->deleteBlogData($id);

        if($result)
            $this->session->set_flashdata('success_msg', 'Record Deleted.');
        else
            $this->session->set_flashdata('error_msg', 'Error.');
        redirect("index.php/Blog_controller/index");
    }
}

?>


Blog_model class

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Blog_model extends CI_Model
{
   
    public function getBlogData()
    {
        $this->db->order_by('created_at', 'desc');
        $query = $this->db->get('blogs');

        if($query->num_rows() > 0)
        {
            return $query->result();
        }
        else
        {
            return false;
        }
    }

    public function saveBlogData()
    {
        $field = array(
            'title'=> $this->input->post('txt_title'),
            'description'=> $this->input->post('txt_description'),
            'created_at'=> date('Y-m-d H:i:s')
        );
        $this->db->insert('blogs',$field);
        if($this->db->affected_rows() > 0)
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    public function getBlogDatabyID($id)
    {
        $this->db->where('id', $id);
        $query = $this->db->get('blogs');

        if($query->num_rows() > 0)
        {
            return $query->result();
        }
        else
        {
            return false;
        }
    }

    public function deleteBlogData($id)
    {
        $this->db->where('id', $id);
        $this->db->delete('blogs');

        if($this->db->affected_rows() > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

?>

blog_view class


            <h5>Blog List</h5><br>

            <?php

            if($this->session->flashdata('success_msg'))
            {
            ?>
                <div class="alert alert-success" role="alert">
                  <?php echo $this->session->flashdata('success_msg'); ?>
                </div>
            <?php
            }
            elseif ($this->session->flashdata('error_msg'))
            {?>
                <div class="alert alert-danger" role="alert">
                  <?php echo $this->session->flashdata('error_msg'); ?>
                </div>
            <?php
            }
            ?>

            <a href="<?php echo base_url('index.php/Blog_controller/add');?>" class="btn btn-info">Add New</a><br><br>
            <table class="table table-striped table-bordered">
                    <thead>
                        <th>ID</th>
                        <th>Title</th>
                        <th>Description</th>
                        <th>Created At</th>
                        <th>Action</th>
                    </thead>
                    <tbody>

                        <?php
                            if($blogs_result)
                            {
                                foreach ($blogs_result as $blog)
                                    { ?>
                                        <tr>
                                        <td><?php echo $blog->id; ?></td>
                                        <td><?php echo $blog->title; ?></td>
                                        <td><?php echo $blog->description; ?></td>
                                        <th><?php echo $blog->created_at; ?></td>
                                        <td>
                                            <a href="<?php echo base_url('index.php/Blog_controller/edit/'.$blog->id);?>" class="btn btn-light">Edit</a>
                                            <a href="<?php echo base_url('index.php/Blog_controller/delete/'.$blog->id);?>" class="btn btn-danger">Delete</a>
                                        </td>
                                        </tr>
                              <?php }
                            }
                        ?>
                    </tbody>
            </table>
    

add_view class

            <h5>Add New</h5><br>
            <a href="<?php echo base_url('index.php/Blog_controller/index');?>" class="btn btn-info">Back</a><br><br>
   
            <form method="post" action="<?php echo base_url('index.php/Blog_controller/submit');?>" >
                  <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" class="form-control" name="txt_title" id="title" placeholder="Blog Title..." required="true">
                  </div>
                  <div class="form-group">
                    <label for="description">Description</label>
                    <input type="text" class="form-control" name="txt_description" id="description" placeholder="Blog Description..." required="true">
                  </div>
                  <div class="form-group">
                      <input type="submit" class="btn btn-success" name="submitbtn" value="Submit">
                  </div>
            </form> 

edit_view class

            <h5>Edit Blog</h5><br>
            <a href="<?php echo base_url('index.php/Blog_controller/index');?>" class="btn btn-info">Back</a><br><br>
   

            <form method="post" action="<?php echo base_url('index.php/Blog_controller/update');?>" >
                  <input type="hidden" value="<?php echo $blogs_result->id; ?>" name="hidden_id" id="hidden_id" >
                  <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" class="form-control" value="<?php echo $blogs_result->title; ?>" name="txt_title" id="title" required="true">
                  </div>
                  <div class="form-group">
                    <label for="description">Description</label>
                    <input type="text" class="form-control" value="<?php echo $blogs_result->description; ?>"  name="txt_description" id="description" required="true">
                  </div>
                  <div class="form-group">
                      <input type="submit" class="btn btn-success" name="updatebtn" value="Update">
                  </div>
            </form>

Friday, June 12, 2015

Web Services With Visual Studio .NET & C# , Java Web Services Client

hey coders.

In this post I'm going to show you
  • how to create a web service.
  • how to use that created web service through another program.
 How to create a web service

1. Visual Studio -> New Project -> Web category -> ASP.NET Web Service Application.
    Create a web service application (server side) called “TempConverter_ASP.NET_Server".

2. When the Project is created, you get a Service.asmx and a Service.asmx.cs. You can delete this and
    Proj. R+Click -> add new item -> web service called “Converter”.

3. Inside public class Converter : System.Web.Services.WebService { } remove 'HelloWorld' method & add the methods.

Converter.asmx.cs
_____________________________________________________________________________________

        [WebMethod] // add for methods to indicate that they can be accessed outside the web service
        public string FToC(double F)
        {
            return ((F - 32) * 5 / 9).ToString();
        }
        [WebMethod]
        public string FToK(double F)
        {
            return ((F - 32) * 5 / 9 + 273.15).ToString();
        }
        [WebMethod]
        public string CToF(double C)
        {
            return ((C * 9 / 5) + 32).ToString();
        }
        [WebMethod]
        public string CToK(double C)
        {
            return (C + 273.15).ToString();
        }
        [WebMethod]
        public string KToC(double K)
        {
            return (K - 273.15).ToString();
        }
        [WebMethod]
        public string KToF(double K)
        {
            return ((K - 273.15) * 9 / 5 + 32).ToString();
        }
_____________________________________________________________________________________


4. To test the service you can right click on Converter.asmx in the Solution Explorer in Visual Studio
     and choose "View in Browser".
    The test page displays the Converter service name along with the names of the methods and a link to the service description (WSDL).


How to use that created web service through another program

(C# client)





1. Now create a windows forms application “TempConverter_CSharp_Client" to call the web service you implemented.


2.To access the Converter API which is exposed as a web service you will have to add a Service
    Reference in your project.
    R+clicking on the project in solution explorer -> Add Service Reference.
    In the address box of the displayed enter the location of WSDL for Converter Web Service. (You can copy the url of the WSDL for this). Also enter the name “proxy” in the namespace box in the  window.

3. Add using TempConverter_WebService_Client_CSharp.proxy;

4. Now in the button click event of “Convert now” button...
_____________________________________________________________________________________

         private void button1_Click(object sender, EventArgs e)
        {
            ConverterSoapClient client = new ConverterSoapClient();

            if(comboBox1.Text == "K" && comboBox2.Text == "F")
            {
                label2.Text = "Answer is " + client.KToF(Convert.ToDouble(textBox1.Text));
            }
            if (comboBox1.Text == "K" && comboBox2.Text == "C")
            {
                label2.Text = "Answer is " + client.KToC(Convert.ToDouble(textBox1.Text)) ;
            }
            if (comboBox1.Text == "F" && comboBox2.Text == "K")
            {
                label2.Text = "Answer is " + client.FToK(Convert.ToDouble(textBox1.Text)) ;
            }
            if (comboBox1.Text == "F" && comboBox2.Text == "C")
            {
                label2.Text = "Answer is " + client.FToC(Convert.ToDouble(textBox1.Text)) ;
            }
            if (comboBox1.Text == "C" && comboBox2.Text == "K")
            {
                label2.Text = "Answer is " + client.CToK(Convert.ToDouble(textBox1.Text));
            }
            if (comboBox1.Text == "C" && comboBox2.Text == "F")
            {
                label2.Text = "Answer is " + client.CToF(Convert.ToDouble(textBox1.Text)) ;
            }


        }
_____________________________________________________________________________________


(Java client)

1. First start tomcat server. If you don't have tomcat installed download and install tomcat.
    After installation go to localhost:8080 and check if tomcat is running.

2. Eclipse -> Server Window -> D+Click Tom Cat Server -> Change 3 Port numbers to any port    number (ie: 1005 , 1010 , 1009 ), the R+Click Tom Cat Server -> Start.

3. File -> New -> Other -> Web Services -> Web Service Client -> Copy Paste A public WSDL to service definition -> Drag Left Slider To top Test Client -> "Client Project : ......." to change project name -> next -> select correct Output folder -> Next -> Finish.


Run and check for results.

Hope this helped....
Please leave a comment.
Suggestions for improvements are also welcomed :)

...Happy Coding...   

PHP Insert Update Delete Form With MySQL DB

hey coders.

In this post I'm going to show you a very basic PHP form with Insert Update Delete View actions connected to MySQL DB.
I've installed Wamp 2.5 on my PC.

1.Create connect.php to check connection with MySQL.

connect.php
_____________________________________________________________________________________

<?php

     //to check connection run this file
     $link = mysqli_connect('localhost', 'root', '', 'test');

     if ($link)
     {
         echo ("Connection is succeed");
     }
     else
     {
         echo ("Connection is fail");
     }

?>
___________________________________________________________________________________


2. Create input.php file
    important lines shown in blue.

 input.php
___________________________________________________________________________________

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<title>Form Input Data</title>
</head>

<body>
<table border="1">
  <tr>
    <td align="center">Form Input Employees Data</td>
  </tr>
  <tr>
    <td>
      <table>
        <form method="post" action="insert.php">
        <tr>
          <td>Name</td>
          <td><input type="text" name="name" size="20">
          </td>
        </tr>
        <tr>
          <td>Salary</td>
          <td><input type="number" name="salary" size="40">
          </td>
        </tr>
        <tr>
          <td></td>
          <td align="right"><input type="submit" name="submit" value="Sent"></td>
        </tr>

        </form>
        </table>
      </td>
    </tr>
</table>
</body>
</html>
___________________________________________________________________________________


3. Create insert.php file
  
insert.php
___________________________________________________________________________________

<?php
   
    $link = mysqli_connect('localhost', 'root', '', 'test');
     if(isset($_POST["name"],$_POST["salary"] ))   
    {
        if(!empty($_POST["name"]) && !empty($_POST["salary"]) )
        {
            $name = $_POST["name"];
            $salary = $_POST["salary"];
            $add = "INSERT INTO employees(name,salary)VALUES('$name',$salary)";
            $result = mysqli_query($link, $add);
            if($result)
            {
                //echo("<br>Input data is succeed");
                header("location:search.php");
            }
            else
            {
                echo("<br>Input data is fail");
            }
        }
    }

?>
___________________________________________________________________________________


4. Create search.php file
    important lines shown in blue.
 
search.php
___________________________________________________________________________________

<html>
<head>
<title>Search data</title>
</head>
<body>
<table>
  <tr>
    <td align="center">EMPLOYEES DATA</td>
  </tr>
  <tr>
    <td>
      <table border="1">
      <tr>
        <td>ID</td>
        <td>EMPLOYEES<br>NAME</td>
        <td>SALARY</td>
      </tr>
    <?php
    $link = mysqli_connect('localhost', 'root', '', 'test');
    $search = "SELECT * FROM employees ORDER BY id";
    $result = mysqli_query($link, $search);
    while($data = mysqli_fetch_row($result))
    {
        echo("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td></tr>");
    }
    echo("<br><br><tr><td><strong><a href=\"edit.php\">Edit</a></strong></td></tr>");
    ?>

    </table>
  </td>
</tr>
</table>
</body>
</html>
___________________________________________________________________________________


5. Create edit.php file
    important lines shown in blue.
 
edit.php
___________________________________________________________________________________
 <html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<table>
  <tr>
    <td align="center">DATA</td>
  </tr>
  <tr>
    <td>
      <table border="1">
      <?php
      $link = mysqli_connect('localhost', 'root', '', 'test');

      $edit = "SELECT * FROM employees";
      $result = mysqli_query($link, $edit);
      while ($row = mysqli_fetch_array($result))
      {
        echo ("<tr><td>$row[id]</td>");
        echo ("<td>$row[name]</td>");
        echo ("<td>$row[salary]</td>");
        echo ("<td><strong><a href=\"edit_process.php?id=$row[id]\">Edit</a></strong></td>");
        echo ("<td><strong><a href=\"delete.php?id=$row[id]\">Delete</a></strong></td><br><br>");
        echo ("<td><strong><a href=\"input.php\">Add Employee</a></strong></td>");
      }
      ?>

      </table>
    </td>
   </tr>
</table>
</body>
</html>
___________________________________________________________________________________


6. Create edit_process.php file
    important lines shown in blue.
 
edit_process.php
___________________________________________________________________________________
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Form Edit Data</title>
</head>

<body>
<table border=1>
  <tr>
    <td align=center>Form Edit Employees Data</td>
  </tr>
  <tr>
    <td>
      <table>
      <?php
      $link = mysqli_connect('localhost', 'root', '', 'test');
     
      $id1=$_GET['id'];
     
      $edit = "SELECT * FROM employees where id=$id1 ";
      $result = mysqli_query($link,$edit);
      $row = mysqli_fetch_array($result);
      ?>
      <form method="post" action="edit_btn.php">
      <input type="hidden" name="id" value=" <?php echo "$row[id]" ?> ">
        <tr>       
          <td>Name</td>
          <td>
            <input type="text" name="name" size="20" value="<?php echo "$row[name]"?>">
          </td>
        </tr>
        <tr>
          <td>Salary</td>
          <td>
            <input type="text" name="salary" size="40" value="<?php echo "$row[salary]"?>">
          </td>
        </tr>
        <tr>
          <td align="right">
            <input type="submit" name="submit value" value="Edit">
          </td>
        </tr>
      </form>

      </table>
    </td>
  </tr>
</table>
</body>
</html>
___________________________________________________________________________________


7. Create edit_btn.php file
 
edit_btn.php
___________________________________________________________________________________
<?php

$link = mysqli_connect('localhost', 'root', '', 'test');

$name=$_POST['name'];
$salary=$_POST['salary'];
$id=$_POST['id'];

$update = "UPDATE employees SET name='$name',salary=$salary WHERE id=$id";

mysqli_query($link,$update);

header("location:edit.php");

?>
___________________________________________________________________________________


8. Create delete.php file
 
delete.php
___________________________________________________________________________________
<?php
    $link = mysqli_connect('localhost', 'root', '', 'test');
   
    $id2=$_GET['id'];
    
    $delete = "DELETE FROM employees WHERE id=$id2 ";
    $result = mysqli_query($link,$delete);
    header("location:edit.php");
?>
___________________________________________________________________________________

Hope this helped....
Please leave a comment.
Suggestions for improvements are also welcomed :)

...Happy Coding...    

Sunday, November 17, 2013

C# Windows Form App (Private deployment of SQL Server Compact 3.5 SP2) Error - Stopped working

hey coders.

In this post I'm going to give a solution for the issue I faced when deploying my C# windows form App developed using Private deployment of SQL Server Compact 3.5 SP2.

The issue was after installing the app when I tried to run the application it gave me the following error message.

Description:
  Stopped working

Problem signature:
  Problem Event Name:    CLR20r3
  Problem Signature 01:    ARMS.exe
  Problem Signature 02:    1.0.0.0
  Problem Signature 03:    52845d57
  Problem Signature 04:    System.Data.SqlServerCe
  Problem Signature 05:    3.5.1.0
  Problem Signature 06:    4b743b2d
  Problem Signature 07:    15c
  Problem Signature 08:    12
  Problem Signature 09:    System.Data.SqlServerCe.SqlCe
  OS Version:    6.1.7600.2.0.0.256.1
  Locale ID:    1033

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt


There might be looooooods of other easy ways to find this problem and quickly solve it but this was my first time publishing a C# app & using a compact database...so bear with me :) I'm posting this since I got an up vote for my  question related to this issue in stack-overflow and I'm guessing there are other coders who are in similar messed up situation like I was so I'm trying to help them :)


  • Developing machine WIN 7  x64 
  • Targeted Machine     WIN 7  x86
So I was lost for 2 weeks not knowing what to do for this issue,I kept searching "CLR20r3 System.Data.SqlServerCe.SqlCe error" but no one specifically addressed that exact issue rather everyone gave solutions for specific exceptions occured due to System.Data.SqlServerCe.But I didn't even know what exception occurred this.

So this is how I solved it.
First I saw some posts saying that they tried to debug using Visual Studio to find the exact error.
  • So I installed Visual Studio 2010 on the targeted machine then when I Run the app other than Close The application option it gave debug the application option as well so when debugged It gave me the name of the Exception. It said "SqlServerCeException" :D
  • The I searched for solutions there were tons of solutions first this link grabbed my attention since it was a nice way to really know what went wrong.
  • So I modified my connection code into                                                                                                   
     {
            ..............
            ..............
                                                                                                                                                                           if (conn.State.ToString() == "Closed")
            {
                try
               {
                    conn.Open();  //surround conn.open( ) witha try-catch( ) block
                }
                catch(SqlCeException e)
                {
                    MessageBox.Show(e.Message);
                    ShowErrors(e); //use the
ShowErrors method implemented on the same page
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }          
                                                                                                                                                                              .................                                                                                                                                                 .................                                                                                                                                             }        


//ShowErrors method implementation                                                                                                                                                                                                                                                                  public static string ShowErrors(System.Data.SqlServerCe.SqlCeException e)
        {
            System.Data.SqlServerCe.SqlCeErrorCollection errorCollection = e.Errors;

            StringBuilder bld = new StringBuilder();
            Exception inner = e.InnerException;

            if (!string.IsNullOrEmpty(e.HelpLink))
            {
                bld.Append("\nCommand text: ");
                bld.Append(e.HelpLink);
            }

            if (null != inner)
            {
                bld.Append("\nInner Exception: " + inner.ToString());
            }
            // Enumerate the errors to a message box.
            foreach (System.Data.SqlServerCe.SqlCeError err in errorCollection)
            {
                bld.Append("\n Error Code: " + err.HResult.ToString("X",  System.Globalization.CultureInfo.InvariantCulture));
                bld.Append("\n Message   : " + err.Message);
                bld.Append("\n Minor Err.: " + err.NativeError);
                bld.Append("\n Source    : " + err.Source);

                // Enumerate each numeric parameter for the error.
                foreach (int numPar in err.NumericErrorParameters)
                {
                    if (0 != numPar) bld.Append("\n Num. Par. : " + numPar);
                }

                // Enumerate each string parameter for the error.
                foreach (string errPar in err.ErrorParameters)
                {
                    if (!string.IsNullOrEmpty(errPar)) bld.Append("\n Err. Par. : " + errPar);
                }
            }
            return bld.ToString();
        }                                
                                                                                                                         
  (Newly added lines are shown in blue)   


  • And I published the app again and reinstalled the app then when I tried to run the app before Stopped Working Popup message it gave me another popup message with exact details of the error and it said " Access to the database file is not allowed ".
  • So I doubled check if I typed "|DataDirectory|" instead of the path to the .sdf file,
 eg: connectionString = " Data Source=|DataDirectory|myDB.sdf "
  • Then I went to the app installed location I gave it as "C:\Program Files\ARMS" and with in the ARMS folder was the myDB.sdf file. Then I set the .sdf file permission to allow Full Control for the currently logged-in  profile in the security tab on the properties dialog that I got when I right clicked on the .sdf file.
     Then I tried running the earlier installed app and this time it gave me no errors......
    easy as that :D

    Hope this helped....
    Please leave a comment.
    Suggestions for improvements are also welcomed :)

    ...Happy Coding...    

Wednesday, September 25, 2013

Setting Up A Remote Server In Dreamweaver

Hey coders...
This time the post is about setting up a remote server so you an easily upload the file from your system to that remote server.

per-requisites
  • Sign up in  a web hosting server. (here I'm using 000webhost )
Let's get started...

1) First Create a folder in any directory to save your work(created files,related images,css files etc.)   that will be your local site.
 










2) Now Go to 'Site' in Dreamweaver menu bar on top.
    Then select 'New Site'.
   







3) Then Follow numbered steps as shown in the picture below.


















4) Like shown in the picture above when you select 'Server' select 'Add New Server'















5) To fill next few details 1st I'll login to my 000webhost member account.












6) Out of all project domain created select "Go To CPanel" for the correct proj. domain you wishes to link with local site.









7) Then select "View FTP Details"














Figure 1














8) Now for the window which pops up after clicking "Add New Server" in Step 4
    Add the details.
  
Fill details using details in step 7





















9) Then



















All set.......

10) Now how to upload a file to the server ( you must login to the remote server as shown in step 5) to upload files.





















It should display "Connecting to hoststie...."
Then "puting file...."
If asked weather to put dependent files as well click OK.


Hope this helped....
Please leave a comment.
Suggestions for improvements are also welcomed :)

...Happy Coding...    

.



Tuesday, September 24, 2013

Store An Image In mysql Database PHP

Hey coders....
In this post I'll be showing you how to store a picture inside mysql databse.

1) Create the table as shown in the picture below...
  
 

2) Create database connection file.

db_connection.php
_______________________________________________________________________________

<?php
       
        $dbhost="localhost";
        $dbuser="root";
        $dbpass="test123"; 
        $dbdb="test";      //this is database name

        //conect to mysql
        $connect = mysql_connect($dbhost,$dbuser,$dbpass);
        if (!$connect)
        {
            echo "Failed To Connect To MySql".mysql_error();
        }

        //select database
        $db = mysql_select_db($dbdb,$connect);
        if (!$db)
        {
            echo "Failed To Connect To The Database".mysql_error();
        }

?>
_______________________________________________________________________________

3) Create UploadPic.php

newly added lines shown in blue.

UploadPic.php
 _______________________________________________________________________________
 <?php
include_once("db_connection.php"); //include the earlier created database connection file
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload Picture</title>
</head>

<body>
<form enctype="multipart/form-data" action="UploadPic.php" method="post">
     <input name="imageFile" type="file" size="35" >  <!--file type input-->
     <input type="submit" value="Upload">
</form>

<br>

</body>
</html>



_______________________________________________________________________________
 3) In between break and end-body tags of the above code...
................
................
</form>
<br>
 <!--here add these below lines of code-->
</body>
____________________________________________________________________________
<?php
//['tmp_name'] is accessing the temporary file name property of file type inputs
if(!isset( $_FILES['imageFile']['tmp_name'] )) // if not set
{
    echo "Select a picture";
}
else
{
    // file_get_contents() a built in function to get the content
    $pic = addslashes(file_get_contents($_FILES['imageFile']['tmp_name']) ); //addslashes() to prevent sql injection since we are storing this value to the database
    $pic_name = addslashes($_FILES['imageFile']['name']); //['name'] is accessing the name property of file type inputs
   
    $pic_size = getimagesize($_FILES['imageFile']['tmp_name']);
   
    if($pic_size == FALSE)
    {
        echo "Invalid! That is not an image...";
    }
    else
    {
        $sql = "INSERT INTO pic VALUES('','".$pic_name."','".$pic."')"; //here 'pic' is the table created  can leave first column(id) value empty since it's auto generated
        $queryResult = mysql_query($sql);
      
        //check if sql qury properly executed
        if(!$queryResult)
        {
            echo "Ooops! There was a problem uploading the picture";
        }
        else
        {
            $lastId = mysql_insert_id(); //returns the lastly inserted record id
            echo "Yahooo Image uploaded...";
            echo "<br>";
            echo "<img src=getPic.php?passedId=$lastId >";
          
        }
    }
}
   
?>
 _______________________________________________________________________________

 4) Now create getPic.php file

getPic.php

_______________________________________________________________________________

 <?php
include_once("db_connection.php");

$idVar = addslashes($_REQUEST['passedId']); //  $_REQUEST since we are requesting an id from an <img tag>
$sql = "SELECT * FROM pic WHERE id = $idVar " ;
$queryRes = mysql_query($sql);
$picture = mysql_fetch_array($queryRes);
$pic = $picture['image']; // in picture['image']  , 'image' is database column name

header("Content-type: image/jpeg");
echo $pic;

?>

_______________________________________________________________________________

 If still the picture is not displayed after clicking "Upload" button...

use the below line...
ob_clean();
before 
header("Content-type: image/jpeg"); line

Now it should work.... :)

Hope this helped....
Please leave a comment.
Suggestions for improvements are also welcomed :)

...Happy Coding...    



Sunday, September 22, 2013

DateTime Picker (calender to pick dates) in PHP

Hey Coders... :)
As my very first blog post I'll show you how to create a date-time picker where you get a small calender popup when clicked on the text box.So the selected value/date will be displayed in the text box.

Pre-requisites: 
  • Install a web development platform with Apache, PHP and MySQL (eg: wamp/xamp )  or install Apache, PHP and MySQL separately.
  •  Install a text editor. (better : with features specific to the PHP scripting language. I'm using  Dreamweaver)
  • set up a testing server (localhost).

This is how it'll look like at the end...

So here we go...

1) Create a new php files ( DateTimePicker.php & Duration.php ) .
















2) Add a form with two text boxes with ids of 'from' and 'to' in DateTimePicker.php file
 (Newly added code shown in a blue color,comment lines shown in  red )

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DateTime Picker</title>
</head>

<body>
<div>
     
      <form action="Duration.php" method="post"> <!-- On submit redirect to "Duration.php" file-->


          <table width="263" border="0" cellpadding="1" align="center">
            <tr>
                <td><strong><font size="+1">From :</font></strong></td>
                <td><input type="text" id="from" name="txtFromDate" /></td>
           </tr>
           </table>


      </form> 


</div>

</body>
</html>

-------------------------------------------------------------------------------------------------------------------
After entering above code it'll generate this (preview the code in a browser)



-------------------------------------------------------------------------------------------------------------------





3) Within the <head> tag code below 3 lines

 <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
 <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>



________________________________________________________________________________
DateTimePicker.php (Newly added code shown in a blue color,comment lines shown in  red )


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DateTime Picker</title>
</head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<body>
     
      <div>
     
      <form action="Duration.php" method="post">
      <table width="263" border="0" cellpadding="1" align="center">
      <tr>
        <td><strong><font size="+1">From :</font></strong></td>
        <td><input type="text" id="from" name="txtFromDate" /></td>
      </tr>
      <tr>
        <td><strong><font size="+1">To :</font></strong></td>
        <td><input type="text" id="to" name="txtToDate" /></td>
      </tr>
     </table>
      </form>
     
      </div>
     
</body>
</html>
 
4) Within the <body> tag and <div> code below script

<script>
      $(function() {
          $( "#from" ).datepicker({
              defaultDate: "+1w",
              changeMonth: true,
              numberOfMonths: 1,
              onClose: function( selectedDate ) {
                  $( "#to" ).datepicker( "option", "minDate", selectedDate );
              }
          });
          $( "#to" ).datepicker({
              defaultDate: "+1w",
              changeMonth: true,
              numberOfMonths: 1,
              onClose: function( selectedDate ) {
                  $( "#from" ).datepicker( "option", "maxDate", selectedDate );
              }
          });
      });
      </script>



____________________________________________________________________
DateTimePicker.php (Newly added code shown in a blue color)


 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DateTime Picker</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>

<body>

      <script>
      $(function() {
          $( "#from" ).datepicker({   <!-- #from here 'from' is my textbox id , so you can use  #yourtextboxid instead #from -->
              defaultDate: "+1w",
              changeMonth: true,
              numberOfMonths: 1,
              onClose: function( selectedDate ) {
                  $( "#to" ).datepicker( "option", "minDate", selectedDate );
              }
          });
          $( "#to" ).datepicker({
              defaultDate: "+1w",
              changeMonth: true,
              numberOfMonths: 1,
              onClose: function( selectedDate ) {
                  $( "#from" ).datepicker( "option", "maxDate", selectedDate );
              }
          });
      });
      </script>

    
      <div>
    
      <form action="Duration.php" method="post"><!-- On clcicking submit button redirect to "Duration.php" file-->
      <table width="263" border="0" cellpadding="1" align="center">
      <tr>
        <td><strong><font size="+1">From :</font></strong></td>
        <td><input type="text" id="from" name="txtFromDate" /></td> <!--text box id is 'from' -->
      </tr>
      <tr>
        <td><strong><font size="+1">To :</font></strong></td>
        <td><input type="text" id="to" name="txtToDate" /></td><!--text box id is 'to' -->
      </tr>
      </table>
      </form>
    
      </div>
    
</body>
</html>

All done now when previewed on browser it'll look like this....

Easy as that.......

Hope this helped....
Please leave a comment if did.
Suggestions for improvements are also welcomed :)

...Happy Coding...