Saturday, 17 March 2018

Upload File In Mysql Database using JSP and Servlet




Requirements

1. Servlet APT 3.x.x
 Otherwise through exceptions for getPart Method


2. Mysql Connector-5.1.x
Otherwise through exception for setBlob Method instead we use setBinaryStream


Create Three Files and Table in the Database

1. Upload.jsp
2.FileUploadDBServlet.java (servlet File)
3.Message.jsp

1.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo
</head>
<body>
    <center>
        <h1>File Upload to Database Demo

        <form method="post" action="FileUploadDBServlet" enctype="multipart/form-data">
            <table border="0">
                <tr>
                    <td>Photo: </td>
                    <td><input type="file" name="photo" size="50"/></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Save">
                    </td>
                </tr>
            </table>
        </form>
    </center>
</body></html>


2. FileUploadDBServlet

//package net.codejava.upload;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.servlet.*;
    @WebServlet("/uploadServlet")
@MultipartConfig(maxFileSize = 16177215)    // upload file's size up to 16MB

public class FileUploadDBServlet extends HttpServlet
{

        // database connection settings
        private String dbURL = "jdbc:mysql://localhost:3306/imageupload";
        private String dbUser = "root";
        private String dbPass = "rsb";

        protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
        {
//            // gets values of text fields
//            String firstName = request.getParameter("firstName");
//            String lastName = request.getParameter("lastName");

            InputStream inputStream = null; // input stream of the upload file

            // obtains the upload file part in this multipart request
            Part filePart = request.getPart("photo");
            if (filePart != null) {
                // prints out some information for debugging
                System.out.println(filePart.getName());
                System.out.println(filePart.getSize());
                System.out.println(filePart.getContentType());

                // obtains input stream of the upload file
                inputStream = filePart.getInputStream();
            }

            Connection conn = null; // connection to the database
            String message = null;  // message will be sent back to client

            try {
                // connects to the database
//                //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//                Class.forName("com.mysql.jdbc.Driver");
//                conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
                  try{
                Class.forName("com.mysql.jdbc.Driver");
                }catch(Exception e){System.out.println(e);}
                        conn=DriverManager.getConnection("jdbc:mysql://localhost/imageupload","root","rsb");

                // constructs SQL statement
                String sql = "INSERT INTO imageup (imagep) values (?)";
                PreparedStatement statement = conn.prepareStatement(sql);
                //statement.setString(1, firstName);
                //statement.setString(2, lastName);

                if (inputStream != null) {
                    // fetches input stream of the upload file for the blob column
                    statement.setBinaryStream(1, (InputStream)inputStream,100000);
                }

                // sends the statement to the database server
                int row = statement.executeUpdate();
                if (row > 0) {
                    message = "File uploaded and saved into database";
                }
            } catch (SQLException ex) {
                message = "ERROR: " + ex.getMessage();
                ex.printStackTrace();
            } finally {
                if (conn != null) {
                    // closes the database connection
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
                // sets the message in request scope
                request.setAttribute("Message", message);

                // forwards to the message page
                getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
            }
        }
    }


3. Message.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
    <center>
        <h3><%=request.getAttribute("Message")%></h3>
    </center>
</body>
</html>




Table

create table imageup(image longblog);




Monday, 25 December 2017

Project 2017


Download project reference code


 Download Validation File


Public Class MDI

    Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label3.Text = "Donor"
        Donor.ShowDialog()


    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Panel1.Width <= 78 Then
            Panel1.Width = 78
            Label3.Left = 83
            PictureBox13.Visible = True
            PictureBox14.Visible = True
            PictureBox1.Visible = False

            Timer1.Enabled = False

        Else
            Label3.Left = Label3.Left - 10

            Panel1.Width = Panel1.Width - 10
        End If

    End Sub

    Private Sub PictureBox12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox12.Click
        Timer1.Enabled = True

    End Sub

    Private Sub PictureBox14_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox14.Click
        Timer2.Enabled = True

    End Sub

    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        If Panel1.Width >= 284 Then
            Panel1.Width = 284
            Label3.Left = 305
            PictureBox13.Visible = False

            PictureBox14.Visible = False
            PictureBox1.Visible = True

            Timer2.Enabled = False

        Else
            Label3.Left = Label3.Left + 10

            Panel1.Width = Panel1.Width + 10
        End If

    End Sub

    Private Sub PictureBox7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox7.Click
        End

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        DisplayDonors.ShowDialog()

    End Sub
End Class

Tuesday, 23 May 2017

VB Project 2017


Module Code
==============================================================

Option Explicit

Public con As New Connection
Public rs As New Recordset
Public num As Integer

Public Sub connect()
If con.State = 1 Then
con.Close
End If
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;data Source=D:\Project_2017\project2017.mdb"
con.Open
MsgBox ("Conected")

End Sub

Public Sub num_query(ByVal q As String)

If rs.State = 1 Then
rs.Close
End If
rs.Open q, con, adOpenDynamic, adLockPessimistic
If rs.BOF Then
num = 0
Else
num = rs.Fields(0).Value
End If

End Sub
Public Sub inupdel(ByVal q As String)
If rs.State = 1 Then
rs.Close
End If
rs.Open q, con, adOpenDynamic, adLockPessimistic
End Sub
Public Sub sel_query(ByVal q As String)
If rs.State = 1 Then
rs.Close
End If
rs.CursorLocation = adUseClient
rs.Open q, con, adOpenDynamic, adLockPessimistic

End Sub
=========================================================================

Student Info Form Code
Option Explicit

Private Sub cmdAdd_Click()
Module1.num_query ("select max(s_rl)+1 from student")
txtRl.Text = num
txtRl.Enabled = False
cmdAdd.Enabled = False
cmdSave.Enabled = True
End Sub

Private Sub cmdNext_Click()
rs.MoveNext
If rs.EOF Then
rs.MoveLast
MsgBox ("This is last Record")
End If
Call loaddata
End Sub

Private Sub cmdPrev_Click()
rs.MovePrevious
If rs.BOF Then
rs.MoveFirst
MsgBox ("This is First Record")
End If
Call loaddata
End Sub

Private Sub cmdSave_Click()
If txtAdd.Text <> "" And txtmb.Text <> "" And txtnm.Text <> "" And txtRl.Text <> "" And cmbClass.Text <> "" Then
Module1.inupdel ("insert into student values(" & CInt(txtRl.Text) & ",'" & txtnm.Text & "','" & txtmb.Text & "','" & txtAdd.Text & "','" & cmbClass.Text & "')")
MsgBox "Student Added Successfully", vbInformation + vbOKOnly, "Insertion"
cmdAdd.Enabled = True
cmdSave.Enabled = False
txtRl.Text = ""
txtnm.Text = ""
txtAdd.Text = ""
txtmb.Text = ""
cmbClass.Text = "Select"
Else
MsgBox "Fields Should not be empty", vbCritical + vbOKOnly, "Error"
End If
End Sub

Private Sub cmdSearch_Click()
Dim rl As Integer
If txtSrch.Text <> "" Then
rl = CInt(txtSrch.Text)
Module1.sel_query ("select * from student where s_rl= " & rl & " ")
If rs.BOF Then
txtRl.Text = ""
txtnm.Text = ""
txtAdd.Text = ""
txtmb.Text = ""
cmbClass.Text = "Select"
MsgBox ("Record Not Found")
Else
txtRl.Text = rs.Fields(0).Value
txtnm.Text = rs.Fields(1).Value
txtmb.Text = rs.Fields(2).Value
txtAdd.Text = rs.Fields(3).Value
cmbClass.Text = rs.Fields(4).Value
cmdUpdate.Enabled = True
End If
Else
MsgBox ("Enter Roll no")
End If
End Sub

Private Sub cmdUpdate_Click()
If txtAdd.Text <> "" And txtmb.Text <> "" And txtnm.Text <> "" And txtRl.Text <> "" And cmbClass.Text <> "" Then
Module1.inupdel ("update student set s_name='" & txtnm.Text & "',s_mob='" & txtmb.Text & "',s_add='" & txtAdd.Text & "',s_class='" & cmbClass.Text & "' where s_rl=" & CInt(txtRl.Text) & "")
MsgBox ("Student Info Updated")
Else
MsgBox ("Enter All Fields")
End If
End Sub

Private Sub Command1_Click()
If cmbclssrch.Text = "Select Class to search" Then
MsgBox ("Select Class")
Else
Module1.sel_query ("select * from Student where s_class='" & cmbclssrch.Text & "'")
Set DataGrid1.DataSource = rs
Call loaddata
End If
End Sub

Private Sub Form_Load()
Me.Width = 9450
Me.Height = 7695
Me.Left = 4000
Me.Top = 1000
Module1.sel_query ("select distinct(s_class) from student")
While Not rs.EOF
cmbclssrch.AddItem (rs.Fields(0).Value)
rs.MoveNext
Wend
Module1.sel_query ("select * from student")
Set DataGrid1.DataSource = rs
End Sub

Private Sub loaddata()
txtRl.Text = rs.Fields(0).Value
txtnm.Text = rs.Fields(1).Value
txtmb.Text = rs.Fields(2).Value
txtAdd.Text = rs.Fields(3).Value
cmbClass.Text = rs.Fields(4).Value
End Sub

Private Sub txtmb_KeyPress(KeyAscii As Integer)
'MsgBox (KeyAscii)
If KeyAscii >= 48 And KeyAscii <= 57 Or KeyAscii = 8 Then

Else
MsgBox "Enter only Number", vbCritical + vbOKOnly, "Invalid Input"
KeyAscii = 0
End If
End Sub

Private Sub txtmb_LostFocus()
If Mid(txtmb.Text, 1, 1) >= 7 And Mid(txtmb.Text, 1, 1) <= 9 And Len(txtmb.Text) = 10 Then

Else
MsgBox "Invalid Mobile Number", vbCritical + vbOKOnly, "Invalid Input"
txtmb.SetFocus
End If

End Sub

Private Sub txtnm_KeyPress(KeyAscii As Integer)
If KeyAscii >= 65 And KeyAscii <= 90 Or KeyAscii >= 97 And KeyAscii <= 122 Or KeyAscii = 32 Or KeyAscii = 8 Then
'nothing to do
Else
MsgBox "Enter only alphabets", vbCritical + vbOKOnly, "Invalid Input"
KeyAscii = 0
End If

End Sub

Friday, 17 February 2017

Login validataion in PHP




<?php
include"connect.php";
$un=$_POST['txtuname'];
$up=$_POST['txtpass'];
//echo "$un</br>$up</br>";


$res=pg_query($con,"select count(*) from Users where uname='$un' and upass='$up'");

$r=pg_fetch_array($res);
if($r[0]==1)
{
session_start();
$_SESSION['unm']=$un;
$_SESSION['ups']=$up;

 echo "<script type='text/javascript'>";
                echo "if(confirm('Login Successfully'))document.location='home.html';else document.location='home.html';";
                echo "</script>";

}
else
{

 echo "<script type='text/javascript'>";
                echo "if(confirm('Username or password doesnot match'))document.location='home.html';else document.location='home.html';";
                echo "</script>";

}


?>