PHP-newbie

 

Sưu tập được vài đoạn PHP hay hay.Mình chỉ thích những cái linh tinh nên mấy cái  ni mình vô cùng hứng thú
1.code hiển thị giờ hệ thống.
2.Code up load ảnh vào cơ sở dữ liệu.
3.Phân trang hoàn chỉnh.
4.Load ảnh
5.Trình đơn

*Một số mã nguồn (WordPress, Nukeviet, Joomla, Nucleus, Webshop, Shop di đông, Mail, Xtremedia, Gallery cool, Code tin tức chf, Send mail)
Download :http://www.mediafire.com/?elqszjzeyzv

1.Đoạn code hiển thị giờ hệ thống theo định dạng và ngôn ngữ tiếng việt.

<?php
$str_search = array (
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
"Sun",
"am",
"pm",
":"
);
$str_replace = array (
"Thứ hai",
"Thứ ba",
"Thứ tư",
"Thứ năm",
"Thứ sáu",
"Thứ bảy",
"Chủ nhật",
" phút, sáng",
" phút, chiều",
" giờ "
);
$timenow = gmdate("D, d/m/Y - g:i a.", time() + 7*3600);
$timenow = str_replace( $str_search, $str_replace, $timenow);

echo $timenow;

?>

or:

<!--Code Dong ho JavaScript -->
    <script type="text/javascript">
        function StartTime() {
            var today = new Date();     // Lay ngay hien tai
            var h = today.getHours();   //Lay gio hien tai
            var m = today.getMinutes(); //Lay gio hien tai
            var s = today.getSeconds(); //Lay so giay hien tai

            m = CheckTime(m);
            s = CheckTime(s);

            var hientai;
            if (h > 11) {
                hientai = 'PM';
            }
            else {
                hientai = 'AM';
            }
            document.getElementById('dongho').innerHTML = h + " : " + m + " : " + s + " " + hientai;
            setTimeout("StartTime()", 500);
        }
        function CheckTime(i) {
            if (i < 10) {
                i = "0" + i;
            }
            return i;
        }
    </script>
  
<body onload="StartTime()";>
<div id="dongho" style="font-size:30px; color:Navy"></div>
<script type="text/javascript">
    var day = new Date();
    var weekday = new Array(7);//Tao mang thu trong tuan
    weekday[0] = "Ch? nh?t";
    weekday[1] = "Th? 2";
    weekday[2] = "Th? 3";
    weekday[3] = "Th? 4";
    weekday[4] = "Th? 5";
    weekday[5] = "Th? 6";
    weekday[6] = "Th? 7";
    var months = new Array(12);//Tao mang ngay thang trong tuan
    months[0] = "1";
    months[1] = "2";
    months[2] = "3";
    months[3] = "4";
    months[4] = "5";
    months[5] = "6";
    months[6] = "7";
    months[7] = "8";
    months[8] = "9";
    months[9] = "10";
    months[10] = "11";
    months[11] = "12";
    document.writeln("<h1><font color='Navy'>Hôm nay " + weekday[day.getDay()] + " Ngày " + day.getDate() + "/" + months[day.getMonth()] + "/" + day.getFullYear() + "</font></h1>");
     </script>

2. Code up load ảnh vào cơ sở dữ liệu.
+ Trước hết bạn tạo một file upanh.php với nội dung là: form với type có giá trị file

<?php session_start();?>
<center><form id="form1" name="form1" method="post" action="xuly.php" enctype="multipart/form-data" >
<table><tr><td>anh</td>
<td>
  <input type="file" name="txtanh" />
</td>
</tr>
<tr>
  <td><input type="submit" name="Submit" value="Submit" /></td></tr>
</table></form></center>

chú ý: thuộc tính enctype của form, và name trong thẻ input
+ tạo file xuly.php

<?php session_start();
//ket noi csdl
$connect=mysql_connect("localhost","root","")
	or die("k ket noi voi csdl");
	mysql_select_db("ten csdl",$connect);
	mysql_query("SET NAMES 'UTF8'", $connect);
        //lay cac thuoc tinh cua file
	$file_tmp = isset($_FILES['txtanh']['tmp_name']) ? $_FILES['txtanh']['tmp_name'] : ""; 
	$file_name = isset($_FILES['txtanh']['name']) ? $_FILES['txtanh']['name'] : ""; 
	$file_type = isset($_FILES['txtanh']['type']) ? $_FILES['txtanh']['type'] : ""; 
	$file_size = isset($_FILES['txtanh']['size']) ? $_FILES['txtanh']['size'] : ""; 
	$file_error = isset($_FILES['txtanh']['error']) ? $_FILES['txtanh']['error'] : "";
	//-->Tranh tinh trang khi UPDATE images co the tru`ng ten len de them ngay gio he thong.
	$ngaygio=date("Y")."_".date("m")."_".date("d")." ".date("H")."_".date("i")."_".date("s");
	$tenanh=$ngaygio.$file_name;
	//echo $file_error;
	//echo $file_size;
	//echo $file_name;
	//echo $tenanh;
	copy ($file_tmp,$folder.$tenanh); 
	$sql="INSERT INTO ten_bang(hinhanh) VALUES('$tenanh')";
	mysql_query($sql,$connect);
	?>

3.CODE PHÂN TRANG:
Tạo file list.php có code hoàn chỉnh như sau:

<?php

$page = isset ( $_GET["page"] ) ? intval ( $_GET["page"] ) : 1;
$rows_per_page = 20;
$page_start = ( $page - 1 ) * $rows_per_page;
$page_end = $page * $rows_per_page;
$sql_query = mysql_query("SELECT * FROM table_name");
$number_of_page = ceil ( mysql_num_rows( $sql_query ) / $rows_per_page );
if ( $number_of_page > 1 )
{
$list_page = " <td> Trang: </td>";
for ( $i = 1; $i <= $number_of_page; $i++ )
{
if ( $i == $page )
{
$list_page .= " <td>[ <b>{$i}</b> ]</td> ";
}
else
{
$list_page .= "<td><a href='list.php?page={$i}'> {$i} </a></td>";
}
}
}
$i = 0;
while ( $result = mysql_fetch_array ( $sql_query ) )
{
if ( $i >= $page_start )
{
print "";
}

$i++;

if ($i >= $page_end)
{
break;
}
}
print <<<EOF
<table cellspacing="0" cellpadding="0" border="0">
<tr>
{$list_page}
</tr>
</table>
EOF;
?>

*Giải thích:Cú pháp của đoạn này là:
Page = kiểm tra xem biến page có tồn tại hay không [?]
nếu tồn tại thì lấy giá trị của biến này và dùng hàm intval lọc dể nhận được giá trị an toàn [:]
còn nếu không thì sẽ có giá trị mặc định là 1
$page = isset ( $_GET[“page”] ) ? intval ( $_GET[“page”] ) : 1;
**Số dòng trên 1 trang:$rows_per_page = 20;
**Tính số dòng ở trang mở đầu dựa theo biến $page:$page_start = ( $page – 1 ) * $rows_per_page;
**Tính số dòng ở trang cuối dựa theo biến $page: $page_end = $page * $rows_per_page;
Ví dụ về trang mở đầu và trang cuối theo công thức trên:
Giả sử trang đang xem hiện giờ là 1, ta đc: $page_start = (1 – 1) * 20 = 0
Còn $page_end = 1 * 20 = 20, vậy ta có giá trị 0 là mở đầu và 20 là kết thúc
**Truy xuất vào table_name:$sql_query = mysql_query(“SELECT * FROM table_name”);
**Tính toán số trang, cách làm như sau:
“mysql_num_rows( $sql_query )” là lấy tổng số dòng của table đã truy xuất [1]
“$rows_per_page” là bằng 20 (giá trị mà ta đặt ở trên) [2]
Lấy [1] chia cho [2] ta sẽ ra được số trang
Để làm tròn các giá trị từ (x.1 -> x.9 thành 1+x) ta dùng hàm ceil()
$number_of_page = ceil ( mysql_num_rows( $sql_query ) / $rows_per_page );
**Nếu số trang lớn hơn 1 thì sẽ tiến hành liệt kê các trang

if ( $number_of_page > 1 )
{
$list_page = " <td> Trang: </td>";

// Tiến hành in từng trang
for ( $i = 1; $i <= $number_of_page; $i++ )
{
// Nếu $i bằng $page hiện giờ sẽ in đậm để nhận biết đang xem trang nào
if ( $i == $page )
{
$list_page .= " <td>[ <b>{$i}</b> ]</td> ";
}
// Ngược lại...
else
{
$list_page .= "<td><a href='list.php?page={$i}'> {$i} </a></td>";
}
}
}

**Đặt biến $i bằng 0:$i = 0;Liệt kê tất cả các dòng trong 1 table
**Ở trên ta đã nạp nội dung cho biến $list_page, bây giờ thì in nó ra

print <<<EOF
<table cellspacing="0" cellpadding="0" border="0">
<tr>
{$list_page}
</tr>
</table>
EOF;

4.Load ảnh

<!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>Untitled Document</title>
<script type ="text/javascript">
    var img = new Array();
    function LoadHinh()
    {
        img[0] = "anh1.jpg"; //Nho dat cac hinh anh cung thu muc file *.html
        img[1] = "anh2.jpg";
        img[2] = "anh3.jpg";
        
    }LoadHinh();
    var b = 0;
    function BienDoi()
    {
        document.getElementById('anh').src = img[b];
        b++;
        if(b>img.length-1)
        {
            b = 0;
        }
        setTimeout("BienDoi()",2000);
    }
   
    </script>
</head>
<body onload ="BienDoi()">
<img id ="anh" />
</body>
</html>

5.trình đơn javascript
Chèn đoạn js sau trong phần <head>:

<script type="text/javascript">
if (document.getElementById) {
document.write('<style type="text/css">.texter {display:none; border-left:white 20px solid; color:#404040; font: .9em verdana, arial, helvetica, sans-serif; margin-bottom: 12px;}</style>') }

var divNum = new Array("a1","a2","a3"); // at the left you should add a1, a2 etc. for each header you wish to include
// so if you want 4 headers you should add a1, a2, a3, a4 in the format shown
// enclosed in double quotes
function openClose(theID) {
for(var i=0; i < divNum.length; i++) {
if (divNum[i] == theID) {
if (document.getElementById(divNum[i]).style.display == "block") { document.getElementById(divNum[i]).style.display = "none" }
else {
document.getElementById(divNum[i]).style.display = "block"
}
} else {
document.getElementById(divNum[i]).style.display = "none"; }
}
}
</script>

Mã html trong <body>:

<div onclick="openClose('a1')">1] Example & Explanation:</div>
<div style="display: none;" id="a1">
Ma quande lingues coalesce, li grammatica del resultant lingue es plu
simplic e regulari quam ti del coalescent lingues. Li nov lingua franca
va esser plu simplic e regulari quam </div>

<div onclick="openClose('a2')">2] Compatibility:</div>
<div style="display: none;" id="a2">
Epsum factorial non deposit quid pro quo hic escorol. Olypian quarrels
et gorilla congolium sic ad nauseum. Souvlaki ignitus carborundum e
pluribus unum. Defacto lingo est igpay atinlay. Marquee selectus </div>

<div onclick="openClose('a3')">3] Notes:</div>
<div style="display: none;" id="a3">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
</div>