Common PHP code (essential for beginners)

Source: Internet
Author: User

1. Connect to the MySQL database Code
<? PHP
$ Connec = mysql_connect ("localhost", "root", "root") or die ("cannot connect to the database server:". mysql_error ());
Mysql_select_db ("liuyanben", $ connec) or die ("the database cannot be selected:". mysql_error ());
Mysql_query ("set names 'gbk '");
?>

2. Read the database and implement cyclic output
<? PHP
$ SQL = "select * From liuyan order by ly_id DESC ";
$ Conn = mysql_query ($ SQL, $ connec );
While ($ rs = mysql_fetch_array ($ conn )){
?>
Loop content .........
<? PHP
}
?>

3. How to Implement paging, including two functions and two calls
1) two functions
// paging function
function genpage (& $ SQL, $ page_size = 2)
{< br> global $ prepage, $ nextpage, $ pages, $ sums; // out Param
$ page = $ _ Get ["page"];
$ eachpage = $ page_size;
$ pagesql = strstr ($ SQL, "from");
$ pagesql = "select count (*) as IDS ". $ pagesql;
$ conn = mysql_query ($ pagesql) or die (mysql_error ();
if ($ rs = mysql_fetch_array ($ conn )) $ sums = $ Rs [0];
$ pages = Ceil ($ sums-0.5 )/ $ Eachpage)-1;
$ pages = $ pages> = 0? $ Pages: 0;
$ prepage = ($ page> 0 )? $ Page-1: 0;
$ nextpage = ($ page <$ pages )? $ Page + 1: $ pages;
$ startpos = $ page * $ eachpage;
$ SQL. = "Limit $ startpos, $ eachpage";
}< br> // display page
function showpage ()
{< br> global $ page, $ pages, $ prepage, $ nextpage, $ querystring; // Param from genpage function
$ shownum = 10/2;
$ startpage = ($ page >=$ shownum )? $ Page-$ shownum: 0;
$ endpage = ($ page + $ shownum <= $ pages )? $ Page + $ shownum: $ pages;

echo "Total". ($ pages + 1). "Page:";
if ($ page> 0) echo " homepage ";
if ($ startpage> 0)
echo "... ? ";
for ($ I = $ startpage; $ I <= $ endpage; $ I ++)
{< br> if ($ I = $ page) echo " [". ($ I + 1 ). "] ";
else echo " ". ($ I + 1 ). "";
}< br> if ($ endpage <$ pages)
echo " ? ... ";
if ($ page <$ pages)
echo" last page ";
}< br> // display the page with classification
function showpage1 ()
{< br> $ fenlei =$ _ Get ["fenleiid"];
global $ page, $ pages, $ prepage, $ nextpage, $ querystring; // Param from genpage function
$ shownum = 10/2;
$ startpage = ($ page >=$ shownum )? $ Page-$ shownum: 0;
$ endpage = ($ page + $ shownum <= $ pages )? $ Page + $ shownum: $ pages;

Echo "Total". ($ pages + 1). "Page :";
If ($ page> 0) echo "<a href = $ php_self? Fenleiid = $ fenlei & page = 0 $ querystring> homepage </a> ";
If ($ startpage> 0)
Echo "... <B> <a href = $ php_self? Fenleiid = $ fenlei & page = ". ($ page-$ shownum * 2)." $ querystring>? </A> </B> ";
For ($ I = $ startpage; $ I <= $ endpage; $ I ++)
{
If ($ I = $ page) echo "<B> [". ($ I + 1). "] </B> ";
Else echo "<a href = $ php_self? Fenleiid = $ fenlei & page = $ I $ querystring> ". ($ I + 1)." </a> ";
}
If ($ endpage <$ pages)
Echo "<B> <a href = $ php_self? Fenleiid = $ fenlei & page = ". ($ page + $ shownum * 2)." $ querystring>? </A> </B> ...";
If ($ page <$ pages)
Echo "<a href = $ php_self? Fenleiid = $ fenlei & page = $ pages $ querystring> last page </a & amp; gt ;";
}
?>
2) Two Calls
First
<? PHP
$ SQL = "select * From liuyan order by ly_id DESC ";
Genpage ($ SQL); // you only need to add this line to the normal code.
$ Conn = mysql_query ($ SQL, $ connec );
While ($ rs = mysql_fetch_array ($ conn )){
?>
Second
<? PHP
}
?>
<? PHP
Showpage (); // display page
?>
<? PHP
Mysql_close ();
?>

4. server-side inclusion
<? PHP require_once ('conn. php');?>

5. How to Write a record to the database, and then prompt and jump to the page
<? PHP
$ Ly_title = $ _ post ["ly_title"];
$ Ly_content = $ _ post ["ly_content"];
$ Ly_time = $ _ post ["ly_time"];
$ Ly_author = $ _ post ["ly_author"];
$ Ly_email = $ _ post ["ly_email"];
$ SQL = "insert into liuyan (ly_title, ly_content, ly_time, ly_author, ly_email) values ('". $ ly_title. "','". $ ly_content. "','". $ ly_time. "','". $ ly_author. "','". $ ly_email. "')";
Mysql_query ($ SQL, $ connec );
Echo ("<SCRIPT type = 'text/JavaScript '> alert (' added successfully! '); Location. href = 'index. php'; </SCRIPT> ");
?>

6. A dialog box is displayed, and a page Jump occurs.
<? PHP
Echo ("<SCRIPT type = 'text/JavaScript '> alert (' added successfully! '); Location. href = 'index. php'; </SCRIPT> ");
?>

7. Information viewing page (conditional database READING)
1) conditional access to the database
<? PHP
$ SQL = "select * From liuyan where ly_id = $ _ Get [ID]";
$ Conn = mysql_query ($ SQL, $ connec );
$ Rs = mysql_fetch_array ($ conn );
?>
2) Output A Field
<? = $ Rs [ly_title]?>
3) shut down the database
<? PHP
Mysql_close ();
?>

8. Update a record in the database and prompt for redirection.
<? PHP
$ Ly_title = $ _ post ["ly_title"];
$ Ly_content = $ _ post ["ly_content"];
$ Ly_time = $ _ post ["ly_time"];
$ Ly_author = $ _ post ["ly_author"];
$ Ly_email = $ _ post ["ly_email"];
$ SQL = "Update liuyan set ly_title = '$ ly_title', ly_content = '$ ly_content', ly_time = '$ ly_time', ly_author = '$ ly_author ', ly_email = '$ ly_email' Where ly_id = $ _ Get [ID] ";
Mysql_query ($ SQL, $ connec );
Echo ("<SCRIPT type = 'text/JavaScript '> alert ('Update successful! '); Location. href =' ../index. php'; </SCRIPT> ");
?>

9. How to delete a record in a database
<? PHP
$ SQL = "delete from liuyan where ly_id = $ _ Get [ID]";
Mysql_query ($ SQL, $ connec );
Echo ("<SCRIPT type = 'text/JavaScript '> alert ('deleted successfully! '); Location. href =' ../index. php'; </SCRIPT> ");
?>

10. How to perform member login verification
<? PHP
Session_start ();
$ Username = $ _ post ["username"];
$ Password = $ _ post ["password"];
$ SQL = "select * from Admin where username = '". $ username. "' & Password = '". $ password ."'";
$ Result = mysql_query ($ SQL, $ connec );
If ($ ROW = mysql_fetch_array ($ result )){
Session_register ("admin ");
$ Admin = $ username;
Echo ("<SCRIPT type = 'text/JavaScript '> alert ('logon successful! '); Location. href = 'admin. php'; </SCRIPT> ");}
Else
{
Echo ("<SCRIPT type = 'text/JavaScript '> alert ('the user name or password you entered is incorrect. Please enter it again! '); Location. href = 'login. php'; </script & gt ;");
}
Mysql_close ();
?>

11. How to check the session (background check page creation)
<? PHP
Session_start ();
If (! Isset ($ _ session ["admin"]) {
Header ("Location: Login. php ");
Exit;
}
?>

12. Verify that the user name and password are filled in (JavaScript)
<Script language = JavaScript>
<! --
Function confirmlogin ()
{
If (document. frmmain. username. value. Length <4 | document. frmmain. username. value = "")
{
Document. frmmain. username. Focus ();
Document. frmmain. username. Select;
Window. Alert ("Enter your username! ");
Return false;
}
If (document. frmmain. Password. value. Length <4)
{
Document. frmmain. Password. Focus ();
Document. frmmain. Password. Select;
Window. Alert ("enter your password! ");
Return false;
}
Return true;
}
// -->
</SCRIPT>

13. Call the editor method in PHP
1) Place the Editor folder in the background management folder.
2) use the following statements to introduce data.
<Input name = "content" type = "hidden" value = ''>
<IFRAME id = "ewebeditor1" src = "ewebeditorphspo2/ewebeditor.htm? Id = content & Style = coolblue "frameborder =" 0 "scrolling =" no "width =" 550 "Height =" 350 "> </iframe>
Note: name of the folder in the ewebeditorphspo2 editor.
Id = content indicates the name of the hidden domain above.

14. loop output (which can be classified)
1) insert a row and a column of tables
<? PHP
$ I = 1;
?>
<Table>
<Tr>
<? PHP
While ($ rs = mysql_fetch_array ($ conn )){
?>
<TD>
Other cyclic tables and outputs
</TD>
<? PHP
If ($ I % 2 = 0 ){
Echo "</tr> <tr> ";
}
$ I ++;
}
?>
</Tr>
</Table>

15. Bind data to the drop-down list box (selected by default when modification is made)
<Select name = "fenleiid">
<? PHP
$ SQL = "select * From fenleibiao ";
$ Conn = mysql_query ($ SQL, $ connec );
While ($ RS1 = mysql_fetch_array ($ conn )){
?>
<Option value = "<? = $ RS1 ["fenleiid"]?> "
<?
If ($ Rs ["fenleiid"] = $ RS1 ["fenleiid"]) {
Echo "selected ";
}
?>
<? = $ RS1 ["flname"]?>
</Option>
<? Php>
}
?>
</SELECT>

16. Get the character length Function
Strlen ($ c)> 12

17. Define a character truncation Function
Usage: <? = Substrgb ($ Rs ["title"], 10)?>
Function substrgb ($ in, $ num ){
$ Pos = 0;
$ Out = "";
While ($ c = substr ($ in, $ POs, 1 )){
If ($ c = "\ n") break;
If (ord ($ c) & gt; 128 ){
$ Out. = $ C;
$ POS ++;
$ C = substr ($ in, $ POs, 1 );

$ Out. = $ C;
} Else {
$ Out. = $ C;
}
$ POS ++;
If ($ POS> = $ num) break;
}
If ($ out! = $ In) $ out = $ out ."...";
Return $ out;
}

18. Determine if it is a number
! Is_numeric (qq)

19. Obtain the current date in PHP Technology
$ Ptime = date ("Y-m-d ");

20. php verification used for user registration Program
If ($ admin = "" or (strlen ($ admin)> 16) or (strlen ($ admin) <2 )){
Echo "<script language = JavaScript> alert ('Enter the user name (cannot be greater than 16 or less than 2 )');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
If ($ Password = "" Or strlen ($ password)> 16 or strlen ($ password) <6 ){
Echo "<script language = JavaScript> alert ('password is 6-16 characters ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
If ($ Password = ""){
Echo "<script language = JavaScript> alert ('Confirm password cannot be blank ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
} Else {
If ($ password! = $ Password1 ){
Echo "<script language = JavaScript> alert ('inconsistent password with confirm password ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
}
If ($ Wt = ""){
Echo "<script language = JavaScript> alert ('password cannot be blank ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
If ($ da = ""){
Echo "<script language = JavaScript> alert ('answer cannot be blank ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";

}
If ($ QQ! = ""){
If (! Is_numeric ($ qq )){
Echo "<script language = JavaScript> alert ('qq number must be number ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
}
If ($ youbian = "" Or strlen ($ youbian )! = 6 ){
Echo "<script language = JavaScript> alert ('Enter the zip code correctly ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
If ($ youbian! = ""){
If (! Is_numeric ($ youbian )){
Echo "<script language = JavaScript> alert ('zip code must be a number ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
}
If ($ dizhi = ""){
Echo "<script language = JavaScript> alert ('address cannot be blank ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
If ($ mail = ""){
Echo "<script language = JavaScript> alert ('e-mail cannot be blank! ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
If ($ textarea = ""){
Echo "<script language = JavaScript> alert ('personal instructions cannot be blank! ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}
If ($ textarea = "" Or strlen (textarea)> 150 ){
Echo "<script language = JavaScript> alert ('personal Description: 150 characters ');";
Echo "This. Location. href = 'vbscript: history. Back () '; </SCRIPT> ";
}

24. Determine the output content to output other results
<? PHP
If ($ Rs ["active"] = 1 ){
Echo "<font color = '# ff0000'> activation </font> ";
} Else {
Echo "disabled ";
}
?>

25. Character truncation Function
<? = Substr ("$ Rs [zixun_biaoti]", 0, 28)?>

26. Male or single choice questions
<Input type = "radio" name = "hy_zhuangtai" value = "male" <? PHP if ($ Rs ["hy_zhungtai"] = "male") {echo "checked" ;}?>> Male
<Input type = "radio" name = "hy_zhuangtai" value = "" <? PHP if ($ Rs ["hy_zhuangtai"] = "") {echo "checked" ;}?>> Female

27. single choice without single answer

Lock
else {?>
unlock

its save page is

$ hy_id = $ _ Get ['id'];
$ action = $ _ Get ['action'];
if ($ action = 'yes') {
$ SQL = "Update hybiao set hy_zhuangtai = 'lock' where hy_id = '$ id '";
$ query = mysql_query ($ SQL, $ connec);
echo (" ");
}< br> else {
$ SQL = "Update hybiao set hy_zhuangtai = 'normal' where hy_id = '$ id '";
$ query = mysql_query ($ SQL, $ connec);
echo (" ");
}< br> mysql_close ();
?>

28. If the text is too long, the excessive text will be displayed as a ellipsis.
<Div style = "width: 120px; Height: 50px; Border: 0px solid blue; overflow: hidden; text-overflow: ellipsis">
<Nobr> for example, a row of text is long and cannot be displayed in a table. </nobr>
</Div>

29.
Prohibit copying, drag and select
<Body ondragstart = Window. event. returnvalue = false oncontextmenu = Window. event. returnvalue = false onselectstart = event. returnvalue = false>
30. Changes in large text and small text
<SCRIPT type = "text/JavaScript">
Function dozoom (size)
{Document. getelementbyid ('zoom '). style. fontsize = size + 'px ';}
</SCRIPT>
<Span id = "zoom"> text to be specified </span>
<A href = "javascript: dozoom (16)"> large </a> <a href = "javascript: dozoom (14) "> medium </a> <a href =" javascript: dozoom (12) "> small </a>

30. Add to favorites and set as Homepage
<A href = # onclick = "this. style. behavior = 'url (# default # homepage) '; this. setHomePage ('HTTP: // www.makewing.com/lanren/'); "> set as homepage </a>
<A href = "javascript: window. External. AddFavorite ('HTTP: // www.makewing.com/lanren/', 'Lazy gallery')"> Add to favorites </a>

31. Record and display the last modification time of the webpage
<Script language = JavaScript>
Document. Write ("Last Update time:" + document. lastmodified + "")
</SCRIPT>

32. Holiday countdown
<Script language = "JavaScript">
VaR TimeDate = new date ("October 1,2002 ");
VaR times = "National Day ";
VaR now = new date ();
VaR date = TimeDate. gettime ()-Now. gettime ();
VaR time = math. Floor (Date/(1000*60*60*24 ));
If (Time> = 0)
Document. Write ("now" + times + "and:" + time + "day ")
</SCRIPT>

33. Open a window to maximize
<Script language = "JavaScript">
<! -- Begin
Self. moveTo (0, 0)
Self. resizeTo (screen. availwidth, screen. availheight)
// End -->
</SCRIPT>

34. Add background music
<Bgsound src = "mid/windblue [1]. Mid" loop = "-1"> only applicable to IE
<Embed src = "music. Mid" autostart = "true" loop = "true" hidden = "true"> applicable to both Netscape and IE

35. Scroll
<Marquee direction = up Height = 146 onmouseout = start () onmouseover = stop () scrollamount = 2>
Scroll Information
</Marquee>

36. When you click an empty link, the page is often reset to the top.
The Code "javascript: void (null)" replaces the original "#" mark

37. You cannot right-click it, or press Ctrl + A to copy it!
<Body oncontextmenu = "window. event. returnvalue = false"
Onkeypress = "window. event. returnvalue = false"
Onkeydown = "window. event. returnvalue = false"
Onkeyup = "window. event. returnvalue = false"
Ondragstart = "window. event. returnvalue = false"
Onselectstart = "event. returnvalue = false">
</Body>

37. Random conversion of background images (a special effect that refreshes the mood)
<Script language = "JavaScript">
Image = new array (4); // defines the image as an array of the number of images.
Image [0] = 'tu0.gif '// path of the background image
Image [1] = 'tu1.gif'
Image [2] = 'tu2.gif'
Image [3] = 'tu3.gif'
Image [4] = 'tu4.gif'
Number = math. Floor (math. Random () * image. Length );
Document. Write ("<body background =" + image [number] + "> ");
</SCRIPT>

38. Move the mouse over the link
Style = "cursor: hand"

39. How to close the Layer
<Div id = "layer1"> </div>
<A href = "#" onclick = "layer1.style. Display = 'none'"> close layer </a>

40. <a href = javascript: Close ()> [close the window] </a>

41. The concave text background is gray
<Div style = "width: 300px; padding: 20px; overflow: hidden; Word-wrap: Break-word; Word-break: Break: All; font-size: 12px; line-Height: 18px; Background-color: # eeeeee; ">
<Font disabled>
How are you doing? <Br>
Don't you want to try it? <Br>
<A href = "www. lenvo. cnhttp: // www.lenvo.cn/"> www.lenvo.cn </a> </font>
</Div>

42. link the table
<Table width = "100%" onclick = "window. Open ('HTTP: // www.makewing.com/',' _ blank ')" style = "cursor: Hand">
<Tr>
<TD Height = "100" bgcolor = "f4f4f4"> </TD>
</Tr>
</Table>

43. Back & close the window
Back: javascript: history. Back (1)
Close: javascript: window. Close ();

44. If the text is too long, the excessive text will be displayed as a ellipsis.
<Div style = "width: 120px; Height: 50px; Border: 0px solid blue; overflow: hidden; text-overflow: ellipsis">
<Nobr> for example, a row of text is long and cannot be displayed in a table. </nobr>
</Div>

45. prohibit copying. Drag and select

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.