Tuesday, November 30, 2010

Socket Programming (using C/Java) -- Video lecture

Click video to see Video, click tiny up arrow in control bar to return to menu

Monday, November 29, 2010

Algorithm and VC++ Video tutorial


Click video to see Video, click tiny up arrow in control bar to return to menu
C++ for Advance Linux Programming can be found:
http://www.advancedlinuxprogramming.com/alp-folder
for C:  UNIX System Calls and Subroutines using C. 
Free software download::  http://sourceforge.net/
Below is for Windows system, more detail can be found: http://xoax.net

Add feed in blog: Canadian stock market S&P/TSX news and trend


For stock market, I am more interested in Canadian stock market.
I added Canadian stock market news and trend feed at the right sidebar of
this blog.

For how to add feed in your blog:
1) Go to Design-> Add Gadget
2) find feed and add it (+)
3) input the feed url address
4) click continue until done.

Saturday, November 27, 2010

Statistics with R Video tutorial

Click video to see Video, click tiny up arrow in control bar to return to menu
R can be download from http://cran.stat.sfu.ca/index.html
R manual: http://cran.stat.sfu.ca/manuals.html


MATLAB Video tutorial

Click video to see Video, click tiny up arrow in control bar to return to menu
MATLAB documentation:http://www.mathworks.com/help/techdoc/index.html



Thursday, November 25, 2010

Cloud Computing and Amazon CE2 Video introduction

Click links to display in the same window.

Getting Started With Amazon EC2 Cloud Computing Explained Amazon EC2 Service, IN DEPTH


Database Design Video Tutorial

Click links to dsiplay in the same Window.

SQL many-to-many relationships Understanding Normalization Creating Tables in MySQL 5 with Foreign Keys Simple Relationships First Normal Forms 2nd Normal Form 3rd Normal Form


JOHN lennon - Happy Christamas--War is over


Monday, November 22, 2010

vozMe - Convert text to mp3 online


1)Convert text to mp3  online.
Using vozMe http://vozme.com/index.php?lang=en, you can type your text and translate to mp3 online.
2) Speech in your browser.
You can also go to http://vozme.com/bookmarklet.php?lang=en, install the bookmarklet (i.e drag Male voice: vozMe  or Female voice: vozMe to your tool bar in your browser. Using mouse to select (highlight) the text
for speech,  then you click the vozMe button in your browser and you will hear the text.
3) Google translate 
has speech function too. I found the pronunciation in Google translate a little better.

Friday, November 19, 2010

Cluster Computing and MapReduce Lecture

Hadoop MapReduce Releases Download Link.

MapReduce is a patented[1] software frameworkGoogle to support distributed computing on large data sets on clusters of computers.[2] The framework is inspired by map and reduce functions commonly used in functional programming,[3] although their purpose in the MapReduce framework is not the same as their original forms.[4]

MapReduce libraries have been written in C++, C#, Erlang, Java, Ocaml, Python, Ruby, F#, R and other programming languages.

Click video to see Video, click tiny up arrow in control bar to return to menu.

How to add flash effect in your photos?




Source code:
<P align=center>
<TABLE height=323 cellSpacing=0 width=400 background=http://www.fshospital.org.cn/fsyyybbs/Mods/usr/53_14335.jpg border=1>
<TBODY>
<TR>
<TD><EMBED src=http://imgfree.21cn.com/free/flash/51.swf  width=400 height=323 type=application/x-shockwave-flash quality="high" wmode="transparent"></EMBED></TD></TR></TBODY></TABLE></P>
Result:(I add extra music)


snipping tool and Window live movie maker in Windows 7

1) Snipping Tool in Windows 7
Go to All Programs ->Accessories
Click Snipping Tool
You can snapshot any region on your screen.

2) Window live movie maker in Windows
Go to All Programs ->Window live
Click Window live movie maker.
You can add pictures, Videos and music to make movies
and post them in youtube.

Tuesday, November 16, 2010

A nice flower animation


Monday, November 15, 2010

Open-source software vs. closed source

We know a lot of open source software: Apache, Eclipse, FireFox, Java, MySQL, CVS and SVN.
Open source vs. closed source, which is better?


Open-source software (OSS) is computer software that is available in source code form for which the source code and certain other rights normally reserved for copyright holders are provided under a software license that permits users to study, change, and improve the software. Open source licenses meet the requirements of the Open Source Definition.

Open source and free software are somehow similar, but different in the basic idea:
Open source is a development methodology; free software is a social movement.

Research indicates that open-source software have a higher flaw discovery, quicker flaw discovery, and quicker turn around on patches.

Some people think open source software may damage the market of commercial software.
Many company executives could not believe in a product that did not participate economically in a free-market or mixed-market economy.

But open source software may fuel the market for a separate product or service, such as support and installation.

SQL Script to Load an external csv file in tables

1. Suppose we have a table users:
CREATE TABLE `users` ( `id` INT UNSIGNED NOT NULL 
AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 20 ) NOT NULL ) ENGINE = MYISAM;

2. We have a csv file 'c:\Users\jiansen\jiansen_dir\mysqlfile.csv' as:
Tom,1996-12-29
Jerry,1985-12-29
3. We use the following command to insert the csv file in table users in SQL:
LOAD DATA INFILE 'c:/Users/jiansen/jiansen_dir/mysqlfile.csv' INTO TABLE users
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
4. If we use SQL server, we use:
BULK INSERT users
FROM 'c:\Users\jiansen\jiansen_dir\mysqlfile.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = 'n'
)

One trick to blend your Adsense in your blog easily in blogger

1. Go to Setting -> Formatting in your blogger setup
2. Copy your Google content Adsense code in "Post Template"
3. Save setting.
4. After each new post, the Adsense code will show in "Edit HTML"
you can put it in anywhere in your post.

Google DC Talks: The Future of the Internet

Technology is always evolving. So what’s next?
Google vice president Jonathan Zittrain gave a very nice talk as below:


Saturday, November 13, 2010

Add search Keywords in your blog for Search Engine Optimization (SEO)



Go to http://www.checkwebsitestats.com
input your url  and if you found
Keywords:
-= Keyword Not Found,    
Description:
-= Description Not Found =

Yahoo directory: No
then you need to add meta tags in your blogspot for your website Search Engine Optimization (SEO)

For adding to Yahoo directory, go to Yahoo! and input your url.
For  keywords and descriotion:
1. Go to Design->Edit html
2. under <head>
add
<meta content='DESCRIPTION HERE' name='description'/>
<meta content='KEYWORDS HERE' name='keywords'/>
<meta content='AUTHOR NAME HERE' name='author'/> 

DESCRIPTION HERE:Write your blog description
KEYWORDS:Write the keywords of your blog
AUTHOR NAME:Write the author's name(Your name)

Reference reading:
Adding meta tags to blogger(blogspot) blogs,websites-SEO

Check your website or any website value, rank and statistics

Via input your website or any website url in checkwebsitestats.com, you can check the website value, visitor number, rank and
statistics.

Use paypal sandbox to test your code



Use paypal sandbox to test your code related to paypal, the link is as follows:
https://developer.paypal.com/

Use the Sandbox Test Environment to create and manage test accounts and their associated email and API credentials. You can also access valuable developer resources from Help.

How to prevent MySQL injection attacks?

1. What is MySQ injection?
SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

2. Example of MySQL injection.
Suppose we have SQL code:
----------------------------------------------
SELECT fieldlist
  FROM table
 WHERE field = '$EMAIL';
--------------------------------------
By entering EMAIL as "anything' OR 'x'='x",
the resulting SQL is:
-----------------------------------------------
SELECT fieldlist
  FROM table
 WHERE field = 'anything' OR 'x'='x';
------------------------------------------
'x'='x' clause is guaranteed to be true no matter what the first clause is.
This OR clause of 1 will always be true and so every single entry in the "customers" table would be selected by this statement!

3. How to prevent  MySQL injection attacks?

Injection Prevention - mysql_real_escape_string()

What mysql_real_escape_string does is to take a string that is going to be used in a MySQL query and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \'.

prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a

Note: mysql_real_escape_string function
only works if you are already connected to a database.

Example #1 Simple mysql_real_escape_string() example
<?php// Connect
 $link mysql_connect('mysql_host''mysql_user''mysql_password')
    OR die(
mysql_error());
// Query$query sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            
mysql_real_escape_string($user),
            
mysql_real_escape_string($password)); 

?>

Friday, November 12, 2010

How to get menu bar, tool bar or navigation bar back in Firefox?



All you have to do isto press the key at the top that says F10 and then press view, then go to the link that says toolbar and then you will click menu bar, tool bar or navigation bar and then you will have everything back.

Thursday, November 11, 2010

Summary of SQL/MySQL commands



1. Create a table:
CREATE [TEMPORARY] TABLE [table name] ( [column definitions] ) [table parameters].

CREATE TABLE `users` ( `id` INT UNSIGNED NOT NULL 
AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 20 ) NOT NULL ) ENGINE = MYISAM;

Data Type Abbreviations

The following abbreviations are accepted for data type definitions:
Abbreviation
Character

CHAR(n)

CHARACTER(n)

CHAR

CHARACTER

CHAR VARYING(n)

CHARACTER VARYING(n)

VARCHAR(n)

CHARACTER VARYING(n)

VARBINARY(n)

BINARY VARYING(n)

INT(p)

INTEGER(p)

INT

INTEGER

DEC(p, s)

DECIMAL(p, s)

DEC

DECIMAL

NUM(p, s)

NUMERIC(p, s)

NUM

NUMERIC


2. Add a new field:


ALTER TABLE users ADD dateofbirth  DATE  NULL AFTER username;
3. insert into table one row or multi-rows

INSERT INTO table (column1, [column2, ... ]) VALUES (value1, [value2, ...])

INSERT INTO users(username,dateofbirth) VALUES ('John Doe','1996-12-29' ), ('Jiansen Lu','1985-12-29'
 );

4. Select values from tables:
SELECT * from users;
results:
idusernamedataofbirth
1John Doe1996-12-29
2Jiansen Lu1985-12-29

5. group two select  via inner join:
Suppose we have following table:

usernameincome_typeincome
John DoeA2000.0
John DoeB2050.5
Jiansen LuA300.0
Jiansen LuB400.0

We need to produce following output:
username, income from type A, income from type B

CREATE TABLE income
(
   username VARCHAR(20) NOT  NULL,
   income_type CHAR(1) NOT NULL,
income DECIMAL(18,2)NOT NULL
) ENGINE  =  MYISAM;
INSERT INTO income(username,income_type,income) VALUES 
 ('John Doe','A','2000.0' ),
 ('John Doe','B','2050.5' ),
 ('Jiansen Lu','A', '300.0'),
 ('Jiansen Lu','B', '400.0');
select a.username, a.income as incomeA, b.income
 as incomeB from
(
    select * from income where income_type ='A'
) a
inner join
(select * from income where income_type='B'
) b
on a.username = b.username;

username incomeA incomeB
John Doe 2000.00 2050.50
Jiansen Lu 300.00 400.00
 

6. alter the length of varchar:
alter table income modify username VARCHAR(50);

Wednesday, November 10, 2010

Create a forum and three blogs and two sites at orble.com



My WordPress
http://www.jiansenlu.zoka.cc/wordpress/
My orble blogs:
http://www.orble.com/dr-code/
http://www.orble.com/music-video-online-playlist/
http://www.orble.com/fun-photos/ 
took over two abandoned sites: 
http://www.sciencegadget.com/
http://www.codefound.com/ 
When I feel bored, I clicked the ads in neobux,
1 cent per ad.  At the beginning, only maximum
5 ads to click per day. Below is the money I earned.

(You can click the link above to create an account for yourself
to make money by clicking the ads)
I only make a tiny money on Internet.  But I found it is
quite fun. Counting how much cents earned on Internet
each day and how to improve it make me excited.
Bloggers need to persevere through the first 6 months of a blog's life when they are getting very little traffic. After this point blog traffic usually increases very quickly.

Take an abandoned blog from orble.com to make money



Blogs on this list have been inactive for more than 60 days.
If you would like to take over one of these domains, create a blog (click here)
on an appropriate topic and publish 3 posts.

Orble staff will then be automatically notified and will contact you if your blog has been approved for a domain, at which time you can let us know your preference for a domain on this list.

The main advantage to taking over an inactive domain, as opposed to registering a new one, is that it's much easier to attract search engine traffic to older domains. They may also have an established readership or subscription base.

In most cases the old posts on a blog remain in place when a new blogger takes over. Removing the old content may provide you with a clean slate, however it usually reduces your search engine traffic and sometimes causes the domain to be penalized.

If you have any questions please contact:

If you’re looking to earn money online by doing simple job, you can go to Microworkers. Microworkers is about connecting people who need something done (Employers) with people who want to help (Workers). These “things that need to be done” are called “micro jobs”.They will pay you from $0.07 up to $2 for international member and minimum $0.20 for US and canadian membe

Tuesday, November 9, 2010

CSS summary



1. There are three ways of inserting a style sheet:

* External style sheet
* Internal style sheet
* Inline style

External Style Sheet:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>

Internal Style Sheet
<head>
<style type="text/css">
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
</style>
</head>

Inline Styles
<p style="color:sienna;margin-left:20px">This is a paragraph.</p>
result:
This is a paragraph.

2. CSS background:
body {background-color:blue;}
h1 {background-color:blue;}
p {background-color:blue;}
div {background-color:blue;}
body {background-image:url('bg.gif');} //background image

3. CSS text color
body {color:blue;}
h1 {color:#00ff00;}
h2 {color:rgb(255,0,0);}

4. Text Alignment
h1 {text-align:center;}
p.date {text-align:right;}
p.main {text-align:justify;}


5. Text Decoration
a {text-decoration:none;}
h1 {text-decoration:overline;}
h2 {text-decoration:line-through;}
h3 {text-decoration:underline;}
h4 {text-decoration:blink;}

6. Text Transformation
p.uppercase {text-transform:uppercase;}
p.lowercase {text-transform:lowercase;}
p.capitalize {text-transform:capitalize;}

7. Text Indentation
p {text-indent:50px;}
Example:
<p style="text-indent:50px;color:red;background-color:grey;text-decoration:underline">Text indentation 50px.</p>
or
<div style="text-indent:50px;color:red;background-color:grey;text-decoration:underline">Text indentation 50px.</div>
Result:
Text indentation 50px.
8. CSS Font style:
p.normal {font-style:normal;}
p.italic {font-style:italic;}
p.oblique {font-style:oblique;}
9. CSS Font size:
h1 {font-size:40px;}
h2 {font-size:30px;}
p {font-size:14px;}

example:
<div style="font-style:oblique;font-size:30px">font-style:oblique;font-size:30px</div>
result:
font-style:oblique;font-size:30px
9. CSS style links
Color
a:link {color:#FF0000;} /* unvisited link */
a:visited {color:#00FF00;} /* visited link */
a:hover {color:#FF00FF;} /* mouse over link */
a:active {color:#0000FF;} /* selected link */
Text decoration
a:link {text-decoration:none;}
a:visited {text-decoration:none;}
a:hover {text-decoration:underline;}
a:active {text-decoration:underline;}
Background color:
a:link {background-color:#B2FF99;}
a:visited {background-color:#FFFF85;}
a:hover {background-color:#FF704D;}
a:active {background-color:#FF704D;}
10. CSS list:
ul.a {list-style-type: circle;}
ul.b {list-style-type: square;}

ol.c {list-style-type: upper-roman;}
ol.d {list-style-type: lower-alpha;}
11. CSS table
table
{
border-collapse:collapse;
}
table,th, td
{
border: 1px solid black;
}
table
{
width:100%;
}
th
{
height:50px;
}
td
{
height:50px;
vertical-align:bottom;
}
td
{
text-align:right;
}
example:
<table border="2" style="border:10px solid red;background-color:green;text-align:center;width:50%;">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
Result can be found HERE.

Example 1: Link Box:
<style type="text/css">
a:link,a:visited
{
display:block;
font-weight:bold;
color:#FFFFFF;
background-color:#98bf21;
width:120px;
text-align:center;
padding:4px;
text-decoration:none;
}
a:hover,a:active
{
background-color:#7A991A;
}
</style>
<a href="http://www.blogger.com/default.asp" target="_blank">This is a link</a>

Example 2: header
<style type="text/css">
div.header{
padding:0.5em;
color:white;
background-color:gray;
clear:center};
</style>
<div class="header"><h1 class="header"><center>Welcome to My Homepage</center></h1></div>

Results can be seen here
Example 3: CSS drop down menu:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS Dropdown mainmenu Example</title>

<style type="text/css">
<!--
#menuh-container
        {
        position: absolute;
        top: 1em;
        left: 1em;
        }

#menuh
        {
        font-size: small;
        font-family: arial, helvetica, sans-serif;
        width:100%;
        float:left;
        margin:2em;
        margin-top: 1em;
        }

#menuh a
        {
        text-align: center;
        display:block;
        border: 1px solid #555;
        white-space:nowrap;
        margin:0;
        padding: 0.3em;
        }

#menuh a:link, #menuh a:visited, #menuh a:active        /* menu at rest */
        {
        color: white;
        background-color: royalblue;
        text-decoration:none;
        }

#menuh a:hover                                          /* menu on mouse-over  */
        {
        color: white;
        background-color: cornflowerblue;
        text-decoration:none;
        }

#menuh a.top_parent, #menuh a.top_parent:hover  /* attaches down-arrow to all top-parents */
        {
        background-image: url(navdown_white.gif);
        background-position: right center;
        background-repeat: no-repeat;
        }

#menuh a.parent, #menuh a.parent:hover  /* attaches side-arrow to all parents */
        {
        background-image: url(nav_white.gif);
        background-position: right center;
        background-repeat: no-repeat;
        }

#menuh ul
        {
        list-style:none;
        margin:0;
        padding:0;
        float:left;
        width:9em;      /* width of all menu boxes */
        /* NOTE: For adjustable menu boxes you can comment out the above width rule.
        However, you will have to add padding in the "#menh a" rule so that the menu boxes
        will have space on either side of the text -- try it */
        }

#menuh li
        {
        position:relative;
        min-height: 1px;                /* Sophie Dennis contribution for IE7 */
        vertical-align: bottom;         /* Sophie Dennis contribution for IE7 */
        }

#menuh ul ul
        {
        position:absolute;
        z-index:500;
        top:auto;
        display:none;
        padding: 1em;
        margin:-1em 0 0 -1em;
        }

#menuh ul ul ul
        {
        top:0;
        left:100%;
        }

div#menuh li:hover
        {
        cursor:pointer;
        z-index:100;
        }

div#menuh li:hover ul ul,
div#menuh li li:hover ul ul,
div#menuh li li li:hover ul ul,
div#menuh li li li li:hover ul ul
{display:none;}

div#menuh li:hover ul,
div#menuh li li:hover ul,
div#menuh li li li:hover ul,
div#menuh li li li li:hover ul
{display:block;}

/* End CSS Drop Down Menu */
</style>
</head>
<body>
<div id="menuh-container">
<div id="menuh">
        <ul>
                <li><a href="#" class="top_parent">Item 1</a>
                <ul>
                        <li><a href="#" class="parent">Sub 1:1</a>
                              <ul>
                                <li><a href="#">Sub 1:1:1</a></li>
                                <li><a href="#">Sub 1:1:2</a></li>
                                <li><a href="#">Sub 1:1:3</a></li>
                                <li><a href="#">Sub 1:1:4</a></li>
                                </ul>
                         </li>
                        <li><a href="#" class="parent">Sub 1:2</a>
                                <ul>
                                <li><a href="#">Sub 1:2:1</a></li>
                                <li><a href="#">Sub 1:2:2</a></li>
                                <li><a href="#">Sub 1:2:3</a></li>
                                <li><a href="#">Sub 1:2:4</a></li>
                                </ul>
                        </li>
                        <li><a href="#">Sub 1:3</a></li>
                        <li><a href="#" class="parent">Sub 1:4</a>
                                <ul>
                                <li><a href="#">Sub 1:4:1</a></li>
                                <li><a href="#">Sub 1:4:2</a></li>
                                <li><a href="#">Sub 1:4:3</a></li>
                                <li><a href="#">Sub 1:4:4</a></li>
                                </ul>
                        </li>
                        <li><a href="#" class="parent">Sub 1:5</a>
                                <ul>
                                <li><a href="#">Sub 1:5:1</a></li>
                                <li><a href="#">Sub 1:5:2</a></li>
                                <li><a href="#">Sub 1:5:3</a></li>
                                <li><a href="#">Sub 1:5:</a></li>
                                <li><a href="#">Sub 1:5:5</a></li>
                                </ul>
                        </li>
                </ul>
                </li>
        </ul>

        <ul>
                <li><a href="#" class="top_parent">Item 2</a>
                <ul>
                        <li><a href="#" class="parent">Sub 2:1</a>
                                <ul>
                                <li><a href="#">Sub 2:2:1</a></li>
                                <li><a href="#">Sub 2:2:2</a></li>
                                <li><a href="#">Sub 2:2:3</a></li>
                                <li><a href="#">Sub 2:2:4</a></li>
                                </ul>
                        </li>
                        <li><a href="#" >Sub 2:2</a>
                        </li>
                 </li>
        </ul>


</div>  <!-- end the menuh-container div -->
</div>  <!-- end the menuh div -->

</body>
</html>

Results can be seen here

Javascript Summary



1. Single line comments start with //. (note:  HTML comment tag is <!--   My comment -->)
You can declare JavaScript variables with the var keyword:
var x=5;

2. Put Javascript  functions in the head section, this way they are all in one place, and they do not interfere with page content. Both the body and the head section are also fine.  External script is also fine.
<script type="text/javascript" src="myscript.js"></script>Example:

<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>

</head>

<body onload="message()">
</body>
</html>
 3. If Statement
if (condition)
  {
  code to be executed if condition is true
  }
example:
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10

var d=new Date();
var time=d.getHours();

if (time<10)
  {
  document.write("<b>Good morning</b>");
  }
</script>

4. alert box: alert("sometext");
example:
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
<input onclick="show_alert()" type="button" value="Show alert box" />


5. confirm box: confirm("sometext");
example:
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
  {
  alert("You pressed OK!");
  }
else
  {
  alert("You pressed Cancel!");
  }
}
</script>
<input type="button" onclick="show_confirm()" value="Show confirm box" />



6. Prompt Box
prompt("sometext","defaultvalue");
example:
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
  {
  document.write("Hello " + name + "! How are you today?");
  }
}
</script>
<input type="button" onclick="show_prompt()" value="Show prompt box" />


7. For...In Statement
for (variable in object)
  {
  code to be executed
  }
8.  JavaScript Events
By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript.
The onLoad and onUnload events are triggered when the user enters or leaves the page.
The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
 example:
<input type="text" size="30" id="email" onchange="checkEmail()">

The onSubmit event is used to validate ALL form fields before submitting it.
example:
onMouseOver and onMouseOut are often used to create "animated" buttons.
example:
<a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"><img src="w3s.gif" alt="W3Schools" /></a>
W3Schools
8. Javascript data function:
<script type="text/javascript">
function today(){

var today = new Date();

alert("Today is  "+ today);}
</script>
<input type="button" onclick="today()" value="today" />


9. Javascript Math: floor(), min(),max(),randon()
example:
var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);
10. Example: Convert Celsius to Fahrenheit
<script type="text/javascript">
function convert(degree)
{
if (degree=="C")
 {
 F=document.getElementById("c").value * 9 / 5 + 32;
 document.getElementById("f").value=Math.round(F);
 }
else  
 {
 C=(document.getElementById("f").value -32) * 5 / 9;
 document.getElementById("c").value=Math.round(C);
 }
}
</script>
<p></p><b>Insert a number into one of the input fields below:</b></p>
<form>
<input id="c" name="c" onkeyup="convert('C')"> degrees Celsius<br />
equals<br />
<input id="f" name="f" onkeyup="convert('F')"> degrees Fahrenheit
</form>

Insert a number into one of the input fields below:

degrees Celsius

equals

degrees Fahrenheit

Summary of PHP commands (2)



The PHP Date() Function

date(format,timestamp)
  • d - Represents the day of the month (01 to 31)
  • m - Represents a month (01 to 12)
  • Y - Represents a year (in four digits)
echo date("Y-m-d")
produces:  2010-11-09

PHP include() and require Function

The two functions are identical in every way, except how they handle errors:
  • include() generates a warning, but the script will continue execution
  • require() generates a fatal error, and the script will stop
These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages.

PHP file handling:

The fopen() function is used to open files in PHP.

fopen("filenane","option");
option can be  r, r+, w,w+,a,a+,x, x+

PHP file upload:

Detail can be found:

http://www.w3schools.com/php/php_file_upload.asp

PHP cookie:

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. Function:

setcookie(name, value, expire, path, domain);

Detail can be found:
http://www.w3schools.com/php/php_cookies.asp 


PHP Session:

A PHP session variable is used to store information about, or change settings for a user session. Session 
variables hold information about one single user, and are available to all pages in one application.

The session_start() function must appear BEFORE the <html> tag:
session_destroy() will reset your session and you will lose all your stored session data.
Detail can be found:
 http://www.w3schools.com/php/php_sessions.asp


PHP Send mail:

mail(to,subject,message,headers,parameters)
Detail can be found:
http://www.w3schools.com/php/php_mail.asp 
http://www.w3schools.com/php/php_secure_mail.asp 

PHP Error Handling

  • Simple "die()" statements
  • Custom errors and error triggers
  • Error reporting

PHP Exception Handling

With PHP 5 came a new object oriented way of dealing with errors
Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

PHP Filter

A PHP filter is used to validate and filter data coming from insecure sources.

Detail can be found:

http://www.w3schools.com/php/php_filter.asp 


 


Summary of PHP commands (1)



Download PHP
Download PHP for free here:http://www.php.net/downloads.php

Download MySQL for free here:http://www.mysql.com/downloads/

Download Apache for free here:http://httpd.apache.org/download.cgi

1. A PHP scripting block always starts with <?php or <? and end with ?> .All variables in PHP start with a $ sign symbol. A variable does not need to be declared before adding a value to it. PHP sentences end with semicolon;
PHP variable names are case sensitive, but the names of functions are case insensitive. MySQL is not case sensitive by default.
we use // to make a single-line comment or /* and */ to make a large comment block.

PHP array index starts at 0. Example of numeric array:
$cars=array("Saab","Volvo","BMW","Toyota");
$cars[0]="Saab";
Example of associative arrays:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages['Peter'] = "32";

2. if else statement:
if (condition)
{code to be executed if condition is true;}
else
{code to be executed if condition is false;}

switch statement:
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}
for loop

for (init; condition; increment)
{
code to be executed;
}

The foreach loop is used to loop through arrays.

foreach ($array as $value)
{
code to be executed;
}

example:
Code:
<?  $x=array("one","two","three");   foreach ($x as $value)       {   echo $value . " ";  }     ?>
PHP Functions
function functionName()
{
code to be executed;
}

The $_GET Function

The built-in $_GET function is used to collect values from a form sent with
method="get".

The $_POST Function

The built-in $_POST function is used to collect values from a form sent with
method="post".

Example:
Code:
<html> <body>  <form action="welcome.php" method="post">  Name: <input type="text" name="fname" />  Age: <input type="text" name="age" />  <input type="submit" />  </form>  </body>  </html>


welcome.php:

Code:
 <html>  <body>  Welcome <?php echo $_POST["fname"]; ?>!<br />  You are <?php echo $_POST["age"]; ?> years old. </body> </html>

Monday, November 8, 2010

Object Oriented Design in PhP/MySQL

1. index.php,  main webpage


<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once 'Mysql.class.php';

class Test
{
   private $db;

   public function __construct()
   {
      $this->db = Mysql::singleton();
   }

   public function listUserid()
   {
      $result = $this->db->select('SELECT userid, date FROM plus_signup');
      return $result->getTable(true);
   }
}

$test = new Test();
echo $test->listUserid();
?>

The result can be found Here

2. Mysql.class.php, which is used in index.php
<?php
/**
*  Mysql.class.php
*/

/**
*  class used for db query results
*/
require_once 'QueryResult.class.php';

/**
*  "Singleton" pattern MySQL database class
*  @package Database
*/
class Mysql
{

    private $dbHost = 'sql105.zoka.cc:3306';
   private $dbUser = 'jiansen';
   private $dbPwd = 'mypassword';
   private $database = 'userDB';
   private $connx = NULL;
   private $error = '';

   // DO NOT MODIFY BELOW THIS LINE //

   private static $instance;

   /**
   *  Private constructor: prevents direct creation of object
   */
   private function __construct()
   {
      $this->connect();
   }

   /**
   *  Singleton method (only allow one instance of this class)
   *  @return object
   */
   public static function singleton()
   {
      if (!isset(self::$instance))
      {
         $c = __CLASS__;
         self::$instance = new $c;
      }

      return self::$instance;
   }  // end singleton()

   /**
   *  Prevent users from cloning this instance
   *  @return void
   */
   public function __clone()
   {
      trigger_error('Clone is not allowed.', E_USER_ERROR);
   }

   /**
   *  Connect to MySQL and select database
   *  @return boolean
   */
   private function connect()
   {
      $connx = @mysql_connect($this->dbHost, $this->dbUser, $this->dbPwd);
      if($connx != FALSE)
      {
         $this->connx = $connx;
         $db = mysql_select_db($this->database, $this->connx);
         if($db == FALSE)
         {
            $this->error = "Unable to select DB: " . mysql_error();
            user_error($this->error, E_USER_WARNING);
            return(FALSE);
         }
         return(TRUE);
      }
      $this->error = "Unable to connect to DBMS: " . mysql_error();
      user_error($this->error, E_USER_WARNING);
      return(FALSE);
   }  // end connect()

   /**
   *  Get database connection resource ID
   *  @return resource
   */
   public function getConnection()
   {
      return($this->connx);
   }

   /**
   *  Sanitize input for use in SQL
   *  @param string|integer|float $input
   *  @return string|integer|float
   */
   public function sanitize($input)
   {
      $input = trim($input);
      if(!is_numeric($input))
      {
         if(get_magic_quotes_gpc())
         {
            $input = stripslashes($input);
         }
         $input = "'" . mysql_real_escape_string($input) . "'";
      }
      return($input);
   }

   /**
   *  Execute SELECT query (or any query that returns result rows)
   *  @param string $sql
   *  @return object
   */
   public function select($sql)
   {
      if(!$this->connx)
      {
         $this->error = "Cannot process query, no DB connection.";
         user_error($this->error, E_USER_WARNING);
         return(FALSE);
      }
      $result = mysql_query($sql, $this->connx);
      if($result)
      {
         if(mysql_num_rows($result))
         {
            return(new QueryResult($result, $this->connx));
         }
         else
         {
            return(0);
         }
      }
      else
      {
         $this->error = "Query failed ($sql): " . mysql_error();
         user_error($this->error, E_USER_WARNING);
         return(FALSE);
      }
   }

   /**
   *  Execute query that does not return result rows (e.g.: INSERT)
   *  @param string $sql
   *  @return integer
   */
   public function modify($sql)
   {
      if(!$this->connx)
      {
         $this->error = "Cannot process query, no DB connection.";
         user_error($this->error, E_USER_WARNING);
         return(FALSE);
      }
      $result = mysql_query($sql, $this->connx);
      if($result)
      {
         return(mysql_affected_rows($this->connx));
      }
      else
      {
         $this->error = "Query failed ($sql): " . mysql_error();
         user_error($this->error);
         return(FALSE);
      }
   }
}
3. QueryResult.class.php, which is used in Mysql.class.php
<?php
/**
*  Mysql
.class.php
*/

/**
*  Query result from Mysql class
*  @package Database
*/
class QueryResult
{
   private $result = NULL;
   private $connx = NULL;
   private $numRows = 0;

   /**
   *  Constructor
   *  @param resource $result
   *  @param resource $connx
   *  @return void
   */
   public function __construct($result, $connx)
   {
      $this->result = $result;
      $this->connx = $connx;
      $this->numRows = mysql_num_rows($result);
   }

   /**
   *  Get specified result row as assoc. array
   *  @param integer $row
   *  @return array
   */
   public function getRow($row = NULL)
   {
      if($row !== NULL and is_numeric($row))
      {
         if(mysql_data_seek($this->result, abs((int)$row)))
         {
            return(mysql_fetch_assoc($this->result));
         }
      }
      else
      {
         return(false);
      }
   }  // end getRow()

   /**
   *  Get query results as HTML table.
   *  If $headers evaluates a TRUE, a header row will be included.
   *  If $headers is TRUE and the $labels is an array, the values in $labels
   *  will be used as the column heading labels.
   *  @param boolean $headers
   *  @param array $labels
   *  @return string
   */
   public function getTable($headers = FALSE, $labels = NULL)
   {
      if(!mysql_data_seek($this->result, 0))
      {
         return(false);
      }
      $table = "<table class='dbresult'>\n";
      if($headers)
      {
         $table .= "<tr>";
         if(is_array($labels))
         {
            foreach($labels as $label)
            {
               $table .= "<th>$label</th>";
            }
         }
         else
         {
            $num = mysql_num_fields($this->result);
            for($ix = 0; $ix < $num; $ix++)
            {
               $table .= "<th>".mysql_field_name($this->result,$ix)."</th>";
            }
         }
         $table .= "</tr>\n";
      }
      while($row = mysql_fetch_row($this->result))
      {
         $table .= "<tr>";
         foreach($row as $val)
         {
            $table .= "<td>$val</td>";
         }
         $table .= "</tr>\n";
      }
      $table .= "</table>\n";
      return($table);
   }

   /**
   *  Get query results as an array
   *  @return array
   */
   public function getArray()
   {
      mysql_data_seek($this->result, 0);
      $data = array();
      while($row = mysql_fetch_assoc($this->result))
      {
         $data[] = $row;
      }
      return($data);
   }  // end getArray()

   /**
   *  Get query results as an XML string
   *  @return string
   */
   public function getXml()
   {
      mysql_data_seek($this->result, 0);
      $xml = "<?xml version='1.0' encoding='ISO-8859-1'?>\n<data>\n";
      $count = 1;
      while($row = mysql_fetch_assoc($this->result))
      {
         $xml .= "  <record row='$count'>\n";
         foreach($row as $key => $val)
         {
            $xml .= "    <$key>$val</$key>\n";
         }
         $xml .= "  </record>\n";
         $count++;
      }
      $xml .= "</data>";
      return($xml);
   }  // end getXml()

   /**
   *  Free this MySQL result
   *  @return boolean
   */
   public function free()
   {
      return(mysql_free_result($this->result));
   }  // end free()

   /**
   *  Getter for query result resource ID
   *  @return resource
   */
   public function getResultId()
   {
      return($this->result);
   }

   /**
   *  Getter for number of result rows
   *  @return integer
   */
   public function getNumRows()
   {
      return($this->numRows);
   }
}