search
HomeBackend DevelopmentPHP TutorialPHP常用代码大全(新手入门必备)_php基础

1、连接MYSQL数据库代码
$connec=mysql_connect("localhost","root","root") or die("不能连接数据库服务器: ".mysql_error());
mysql_select_db("liuyanben",$connec) or die ("不能选择数据库: ".mysql_error());
mysql_query("set names 'gbk'");
?>

2、读取数据库,并实现循环输出
$sql="select * from liuyan order by ly_id desc";
$conn=mysql_query($sql,$connec);
while($rs=mysql_fetch_array($conn)){
?>
循环的内容.........
}
?>

3、如何实现分页,包括两个函数,两个调用
1)两个函数

//分页函数
function genpage(&$sql,$page_size=2)
{
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$startpos = $page*$eachpage;
$sql .=" limit $startpos,$eachpage ";
}
// 显示分页
function showpage()
{
global $page,$pages,$prepage,$nextpage,$queryString; //param from genpage function
$shownum =10/2;
$startpage = ($page>=$shownum)?$page-$shownum:0;
$endpage = ($page+$shownum
echo "共".($pages+1)."页: ";
if($page>0)echo "首页";
if($startpage>0)
echo " ... ?";
for($i=$startpage;$i{
if($i==$page) echo " [".($i+1)."] ";
else echo " ".($i+1)." ";
}
if($endpageecho "? ... ";
if($pageecho "尾页";
}
//显示带分类的分页
function showpage1()
{
$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
echo "共".($pages+1)."页: ";
if($page>0)echo "首页";
if($startpage>0)
echo " ... ?";
for($i=$startpage;$i{
if($i==$page) echo " [".($i+1)."] ";
else echo " ".($i+1)." ";
}
if($endpageecho "? ... ";
if($pageecho "尾页& amp; gt;";
}
?>
2)两个调用
第一个
$sql="select * from liuyan order by ly_id desc";
genpage($sql); //只需要正常代码加上这一行就ok。
$conn=mysql_query($sql,$connec);
while($rs=mysql_fetch_array($conn)){
?>
第二个
}
?>
showpage(); //显示页
?>
mysql_close();
?>

4、服务器端包含


5、如何将一条记录写入数据库,然后提示并跳转页面
$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("");
?>

6、 弹出对话框,并发生页面跳转
echo("");
?>

7、 信息查看页面(有条件读取数据库)
1)有条件读取数据库
$sql="select * from liuyan where ly_id=$_GET[id]";
$conn=mysql_query($sql,$connec);
$rs=mysql_fetch_array($conn);
?>
2) 将某个字段输出
=$rs[ly_title]?>
3)关闭数据库
mysql_close();
?>

8、对数据库中某一条记录进行更新操作,并作提示跳转
$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("");
?>

9、 如何删除数据库中的一条记录
$sql="delete from liuyan where ly_id=$_GET[id]";
mysql_query($sql,$connec);
echo("");
?>

10、 如何进行会员登录验证
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("");}
else
{
echo("& gt;");
}
mysql_close();
?>

11、如何对SESSION进行检验(后台检查页面的制作)
session_start();
if(!isset($_SESSION["admin"])){
header("location:login.php");
exit;
}
?>

12、 验证用户名及密码是否填写(javascript)


13、 在PHP中调用编辑器的方法
1)将编辑器文件夹放置后台管理文件夹内。
2)利用以下语句进行引入操作。


注:eWebEditorPHP38编辑器文件夹的名称。
id=content中content为上面隐藏域的名称

14、循环输出(能够实现分列)
1)首先插入一行一列表格
$i=1;
?>



while($rs=mysql_fetch_array($conn)){
?>

if ($i % 2==0) {
echo "";
}
$i++;
}
?>


被循环的其它表格和输出


15、 给下拉列表框绑定数据(并且在修改时默认选中)


16、获取字符长度函数
strlen($c)>12

17、 定义一个字符截取函数
用法:=substrgb($rs["title"],10)?>
function substrgb($in,$num){
$pos=0;
$out="";
while($c=substr($in,$pos,1)){
if($c=="\n") break;
if(ord($c)>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、判断是否是数字
!is_numeric(qq)

19、PHP技术中获取当前日期
$ptime=date("y-m-d");

20、用户注册时所使用的PHP验证程序
if ($admin=="" or (strlen($admin)>16) or (strlen($admin)echo "";
}
if ($password=="" or strlen($password)>16 or strlen($password)echo "";
}
if ($password=="") {
echo "";
}else{
if ($password!=$password1) {
echo "";
}
}
if ($wt="") {
echo "";
}
if ($da="") {
echo "";

}
if ($qq!="") {
if (!is_numeric($qq)) {
echo "";
}
}
if ($youbian=="" or strlen($youbian)!=6) {
echo "";
}
if ($youbian!="") {
if (!is_numeric($youbian)) {
echo "";
}
}
if ($dizhi="") {
echo "";
}
if ($mail=="") {
echo "";
}
if ($textarea=="") {
echo "";
}
if ($textarea=="" or strlen(textarea)>150) {
echo "";
}

24、对输出的内容进行判断,从而输出其它结果
if ($rs["active"]==1) {
echo "激活";
}else{
echo "禁用";
}
?>

25.字符截取函数
=substr("$rs[zixun_biaoti]",0,28)?>

26.男女问题或单选带选择的
>男
>女

27.单选不带单选框的

锁定
else{?>
解锁

它的 save页是

$hy_id=$_GET['id'];
$action=$_GET['action'];
if ($action=='yes'){
$sql="update hybiao set hy_zhuangtai='锁定' where hy_id='$id'";
$query=mysql_query($sql,$connec);
echo("");
}
else{
$sql="update hybiao set hy_zhuangtai='正常' where hy_id='$id'";
$query=mysql_query($sql,$connec);
echo("");
}
mysql_close();
?>

28. 如果文字过长,则将过长的部分变成省略号显示

就是比如有一行文字,很长,表格内一行显示不下.


29.
禁止复制,鼠标拖动选取

30.大 中 小 文字的变化

需要指定大小的文字


30.添加到收藏夹和设为首页
设为首页
收藏本站

31.记录并显示网页的最后修改时间


32.节日倒计时


33.打开窗口即最大化


34.加入背景音乐
只适用于IE
对Netscape ,IE 都适用

35.滚动

滚动信息


36.防止点击空链接时,页面往往重置到页首端
代码“javascript:void(null)”代替原来的“#”标记

37.不能点右键,不用CTRL+A,不能复制作!
onkeypress="window.event.returnValue=false"
onkeydown="window.event.returnValue=false"
onkeyup="window.event.returnValue=false"
ondragstart="window.event.returnValue=false"
onselectstart="event.returnValue=false">


37.随机变换背景图象(一个可以刷新心情的特效)


38.划过链接 手型鼠标
style="cursor:hand"

39.如何关闭层

关闭层

40.[关闭窗口]

41.凹陷文字背景为灰色


怎么样,我凹下去了吧?

你不想试试吗?

www.lenvo.cn



42.给表格做链接






43.后退&关闭窗口
后退:javascript:history.back(1)
关闭:javascript:window.close();

44.如果文字过长,则将过长的部分变成省略号显示

就是比如有一行文字,很长,表格内一行显示不下.


45.禁止复制,鼠标拖动选取
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use