Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Thursday, June 6, 2013

AJAX - Request MySQL data through PHP

Suppose we need to get password (actually hash value in database) of a specified user, how we can make that?

We have a form to get user name input and have a button associated with function getResult().
 

getResult()
function getResult() {
    var xmlhttp = new XMLHttpRequest();
    var name = document.getElementById("name").value;
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            setTimeout(function() {document.getElementById("result").innerHTML = xmlhttp.responseText;}, 1000);
        } else {
            document.getElementById("result").innerHTML = "Loading...";
        }
    }
   
    xmlhttp.open("POST", "getuserhash.php");
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("name=" + name);
}

getuserhash.php
include_once('connection.php');

$name = $_POST['name'];

$query = $pdo->prepare("SELECT user_password FROM user WHERE user_name = ?");
$query->bindValue(1, $name);
$query->execute();
$data = $query->fetch();

echo $data["user_password"];

It works!







Use jQuery to rewrite getResult()
        
function getResult() {
    var name = $("#name").val();
    $.post("getuserhash.php", {name:name}, 
        function(data) {
            $("#result").html(data);
        }
    );
}

Tuesday, May 28, 2013

PHP - Store and get date/time value between PHP and MySQL

MySQL has three kinds of date/time attributes: DATETIME, DATE and TIMESTAMP.
  • DATETIME starts from '1000-01-01 00:00:00' and ends up with '9999-12-31 23:59:59'. 
  • DATE is part of DATETIME: YYYY-MM-DD
  • TIMESTAMP starts from '1970-01-01 00:00:01' UTC and ends up with '2038-01-19 03:14:07' UTC. It is still fine today. However, do you still remember Y2P? Will TIMESTAMP be Y2K38P?
Generally speaking, you can use DATETIME for date like birthday, and use TIMESTAMP for anything related to current time. For example, when you add an article, you can use TIMESTAMP. 

In addition, since TIMESTAMP is timezone related, you will get a different value if your change your timezone. TIMESTAMP is also particularly useful in logging because it can be told to be updated on INSERTs and UPDATEs.

In summary, DATETIME represents a date (in calendar) and a time (on clock), while TIMESTAMP represents a well defined point in time.

PHP uses time() to return current Unix timestamp and date() to format a local time/date.

So, suppose we have a DATETIME column in MySQL, how we should store and get the value between PHP and database?

To Store
    
    //
    $datetime = date('Y-m-d h:i:s', time());
    // 2013-05-28 02:10:14

To Get - use strtotime() to parse any English textual datetime description into a Unix timestamp, and then use date() to change the timestamp to any format you would like to show.
    
    //
    $timestamp = strtotime($article["article_time"]);
    $time = date("l jS, F Y", $timestamp); 
    // Tuesday 28th, May 2013

Frequently used format in date().

d
Day of the month
01 to 31
j
Day of the month
1 to 31
S
English ordinal suffix for the day of the month
st, nd, rd or th. Works well with j
D
A textual representation of a day
Mon to Sun
l           
A full textual representation of the day
Sunday to Saturday
m
Numeric representation of a month
01 to 12
n
Numeric representation of a month
1 to 12
M
A short textual representation of a month
Jan to Dec
F
A full textual representation of a month
January to December
Y
A full numeric representation of a year
1999 or 2003
y
A two digit representation of a year
99 or 03
a
Lowercase Ante meridiem and Post meridiem
am or pm
A
Uppercase Ante meridiem and Post meridiem
AM or PM
h
12-hour format of an hour
01 to 12
H
24-hour format of an hour
00 to 23
i
Minutes with leading zeros
00 to 59
s
Seconds, with leading zeros
00 to 59

Set your local timezone with date_default_timezone_set()
//
date_default_timezone_set('Australia/Adelaide');
//

Find all supported timezones at timezones.

Monday, May 27, 2013

PHP - A simple CMS - Online Library

Content Management System (CMS) is a computer system that allows the user to create, edit, delete, and show whatever information they are interested. CMS is often working as a website developed with database, back-end and front-end scripting language.

I have created a simple CMS - Online Library, to simply describe what a CMS looks like.

The system is developed by PHP and MySQL, and running on Apache. Actually, I am using WAMP which you can find at wampserver to deploy the environment.

The system includes:

  • List and show articles (everyone)
  • Add, edit and delete articles (admin)
  • Database and CSS files

See code structure and database tables structure.







See the page and behaviour












Sunday, May 5, 2013

Sample Java MVC Web Application - Part III

In this part, we add JDBC and MySQL to our sample project. Hence, we divide the src package to four parts: entity, jdbc, servlet and test.

Take a look at the project structure -




























Execution Results -














Create data in MySQL -
create database testdb;

use testdb;

create table person (
id int not null auto_increment primary key,
firstname varchar(20),
lastname varchar(20)
);

insert into person (firstname, lastname) values ("James","Bond");
insert into person (firstname, lastname) values ("James","White");

DBConnection.java -
package com.mqin.example.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

    public static Connection getConnection() {
        Connection conn = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb?" + "user=root&password=root");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }
}


PersonOperation.java - 
package com.mqin.example.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mqin.example.entity.PersonModel;

public class PersonOperation {

    private Connection conn = null;

    public PersonOperation() {
        conn = DBConnection.getConnection();
    }

    public void insertPerson(PersonModel p) {
        String sql = "insert into person (firstname, lastname) valus (?,?)";

        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, p.getFirstName());
            ps.setString(2, p.getLastName());
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public PersonModel getPerson(int id) {
        PersonModel p = null;
        String sql = "select * from person where id = ?";

        try {
            PreparedStatement ps = conn.prepareCall(sql);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                p = new PersonModel();
                p.setId(rs.getInt("id"));
                p.setFirstName(rs.getString("firstname"));
                p.setLastName(rs.getString("lastname"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return p;
    }

    public ArrayList<PersonModel> getPerson(String firstname) {
        ArrayList<PersonModel> parray = new ArrayList<PersonModel>();
        String sql = "select * from person where firstname = ?";

        try {
            PreparedStatement ps = conn.prepareCall(sql);
            ps.setString(1, firstname);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                PersonModel p = new PersonModel();
                p.setId(rs.getInt("id"));
                p.setFirstName(rs.getString("firstname"));
                p.setLastName(rs.getString("lastname"));
                parray.add(p);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return parray;
    }

}

PersonTest.java -
package com.mqin.example.test;

import java.util.ArrayList;
import java.util.Iterator;

import com.mqin.example.entity.PersonModel;
import com.mqin.example.jdbc.PersonOperation;

public class PersonTest {

    private PersonOperation pop = null;

    public PersonTest() {
        pop = new PersonOperation();
    }

    public boolean testGetById(int id) {
        PersonModel p = pop.getPerson(id);

        if (p == null) {
            return false;
        }

        log(p.getFirstName() + " " + p.getLastName());
        return true;
    }

    public boolean testGetByFirstName(String firstname) {
        ArrayList<PersonModel> parray = new ArrayList<PersonModel>();
        PersonModel p = null;

        parray = pop.getPerson(firstname);

        if (parray.isEmpty()) {
            return false;
        }

        Iterator<PersonModel> iterator = parray.iterator();

        while (iterator.hasNext()) {
            p = iterator.next();
            log(p.getFirstName() + " " + p.getLastName());
        }

        return true;
    }

    private void log(String string) {
        System.out.println(string);
    }

    public static void main(String[] args) {
        PersonTest pt = new PersonTest();

        int id = 2;
        String firstname = "James";

        if (!pt.testGetById(id)) {
            pt.log("Cannot find person with id = " + id);
        }

        if (!pt.testGetByFirstName(firstname)) {
            pt.log("Cannot find person with firstname = " + firstname);
        }
    }

}


SearchByID.java -
package com.mqin.example.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mqin.example.entity.PersonModel;
import com.mqin.example.jdbc.PersonOperation;

public class SearchByID extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public SearchByID() {
        super();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        if (request.getParameter("id") == null || request.getParameter("id") == "") {
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        int id = (new Integer(request.getParameter("id"))).intValue();
        PersonOperation pop = new PersonOperation();
        PersonModel person = pop.getPerson(id);

        request.setAttribute("person", person);

        getServletContext().getRequestDispatcher("/searchidoutput.jsp").forward(request, response);
    }

}


SearchByFirstName.java -
package com.mqin.example.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mqin.example.entity.PersonModel;
import com.mqin.example.jdbc.PersonOperation;

public class SearchByFirstName extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public SearchByFirstName() {
        super();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        if (request.getParameter("firstname") == null || request.getParameter("firstname") == "") {
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

        String firstName = request.getParameter("firstname");
        PersonOperation pop = new PersonOperation();
        ArrayList<PersonModel> parray = new ArrayList<PersonModel>();
        parray = pop.getPerson(firstName);

        request.setAttribute("parray", parray);

        getServletContext().getRequestDispatcher("/searchnameoutput.jsp").forward(request, response);
    }

}


index.jsp -
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
    <form action="" method="post">
        <table border="0">
            <tr>
                <td>ID:</td>
                <td><input type="text" name="id" /></td>
            </tr>
            <tr>
                <td>First Name:</td>
                <td><input type="text" name="firstname" /></td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td><input type="text" name="lastname" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="SearchByID"
                    onclick="form.action='searchbyid';" /></td>
                <td><input type="submit" value="SearchByFirstName"
                    onclick="form.action='searchbyfirstname';" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

searchidoutput.jsp -
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<jsp:useBean id="person" scope="request" class="com.mqin.example.entity.PersonModel" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
    <table>
        <tr>
            <td>First Name:</td>
            <td><jsp:getProperty name="person" property="firstName" /></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><jsp:getProperty name="person" property="lastName" /></td>
        </tr>
    </table>
</body>
</html>

searchnameoutput.jsp -
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="com.mqin.example.entity.PersonModel"%>
<!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=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
    <table>
        <%
            ArrayList<PersonModel> parray = (ArrayList<PersonModel>) request.getAttribute("parray");
            PersonModel p = null;
            Iterator<PersonModel> iterator = parray.iterator();
            while (iterator.hasNext()) {
                p = iterator.next();
        %>
        <tr>
            <td>Person ID:</td>
            <td><%=p.getId()%></td>
        </tr>
        <tr>
            <td>First Name:</td>
            <td><%=p.getFirstName()%></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><%=p.getLastName()%><%}%></td>
        </tr>
    </table>
</body>
</html>




Wednesday, May 1, 2013

MySQL JDBC

Download mysql-connector-java-xxx.jar from mysql-connector-java

General Steps -
1. load driver
2. create connection
3. create statement (statement) / prepare statement (preparedStatement)
4. exeute query (select) / execute update (update/delete)
5. get resultset
6. close resultset/connection/connection

Sample code of MySQL JDBC access -
package com.mqin.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySQL {
    private Connection conn = null;
    private Statement stmt = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;

    public void queryDataBase() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/world?" + "user=root&password=root");

            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from world.city");
            printResultSet(rs);

            pstmt = conn.prepareStatement("insert into world.city values (default, ?, ?, ?, ?)");
            pstmt.setString(1, "AAA");
            pstmt.setString(2, "BBB");
            pstmt.setString(3, "CCC");
            pstmt.setInt(4, 1000);
            pstmt.executeUpdate();

            pstmt = conn.prepareStatement("SELECT id, name, countrycode, district, population from world.city");
            rs = pstmt.executeQuery();
            printResultSet(rs);

            pstmt = conn.prepareStatement("delete from world.city where name = ? ; ");
            pstmt.setString(1, "AAA");
            pstmt.executeUpdate();

            rs = stmt.executeQuery("select * from world.city");
            printResultSet(rs);
            printMetaData(rs);

        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            close();
        }

    }

    private void printMetaData(ResultSet rs) throws SQLException {
        System.out.println("The columns in the table are: ");

        System.out.println("Table: " + rs.getMetaData().getTableName(1));
        for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
            System.out.println("Column " + i + ": " + rs.getMetaData().getColumnName(i));
        }
    }

    private void printResultSet(ResultSet rs) throws SQLException {

        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String countrycode = rs.getString("countrycode");
            String district = rs.getString("district");
            int population = rs.getInt("population");

            System.out.printf("ID: %-5d Name: %-30s CountryCode: %-5s District: %-20s Population %-10d\n", id, name,
                    countrycode, district, population);
        }
    }

    private void close() {

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                System.out.println("SQLException: " + ex.getMessage());
                System.out.println("SQLState: " + ex.getSQLState());
                System.out.println("VendorError: " + ex.getErrorCode());
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            rs = null;
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                System.out.println("SQLException: " + ex.getMessage());
                System.out.println("SQLState: " + ex.getSQLState());
                System.out.println("VendorError: " + ex.getErrorCode());
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            stmt = null;
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                System.out.println("SQLException: " + ex.getMessage());
                System.out.println("SQLState: " + ex.getSQLState());
                System.out.println("VendorError: " + ex.getErrorCode());
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            conn = null;
        }

    }

    public static void main(String[] args) throws Exception {
        MySQL mysql = new MySQL();
        mysql.queryDataBase();
    }

}


You may meet error with MySQL delete/update query like -
Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Queries and reconnect.

You need to uncheck "safe update" in MySQL preference -
Edit -> Preferences -> SQL Queries -> uncheck "Safe Updates"
Query -> Reconnect to Server