Home Backend Development PHP Tutorial PHP基础开发代码示范

PHP基础开发代码示范

Jun 13, 2016 am 11:00 AM
echo function gt lt

PHP基础开发代码示例~
最近打算重拾PHP来开发一些小型应用,很久没用PHP了,有些语法都生疏了,今天上午写了三个例子,基本上把之前的PHP复习了一下。

基础语法操作:

<?php //输出的方式测试echo '###################输出测试################<br>';echo '测试输出1(单引号)<br>';echo "测试塑出2(双引号)<br>";?>='测试输出3(=表达式)<br>'?> echo '测试输出4(单个表达式)<br>'; ?><?php //类型echo '###################类型测试################<br>';$testInt = 1;$testStr = "字符串";$testFloat = 1.23;$testBoolean = false; //false/true:如果转换成字符串则为空/"1",转换成整型则为0/1$testArray = array("first"=>1,2,3,4,5);$testStr2 = $testStr; //testStr修改,testStr2不会修改$testStr3 = &$testStr; //testStr修改,testStr3也会修改echo '整型:'.$testInt.'<br>';echo '字符串型:'.$testStr.'<br>';$testStr = '字符串修改了';echo '字符串型修改后:'.$testStr.'<br>';echo '字符串型修改后(2):'.$testStr2.'<br>';echo '字符串型修改后(3):'.$testStr3.'<br>';echo '浮点型:'.$testFloat.'<br>';echo '布尔型:'.(int)$testBoolean.'<br>';echo '数组测试(1):'.$testArray[0].'<br>';echo '数组测试(2):'.$testArray['first'].'<br>';print_r($testArray);echo '<br>';foreach ($testArray as $i => $value) {    echo '数组迭代结果:'.$i."->".$value."<br>";}//IO操作echo '##################IO操作####################<br>';echo '读取该文件的内容:<br>';$theFileName = "test_base.php"; //文件名称或者全路径$handle = fopen ($theFileName, "rb");$contents = fread ($handle, filesize ($theFileName));fclose ($handle); echo '<div style="border:1px solid #aaa;color:blue;"><pre class="brush:php;toolbar:false">'.htmlspecialchars($contents).'
Copy after login
';?>

数据库的处理:
<?php //四种引用方式//require 'test_base.php'; //无条件的引用,报错会终止应用,引用的文件只处理一次//require_once 'test_base.php'; //无条件的引用,报错会终止应用,引用的文件只处理一次并只显示一次//include 'test_base.php'; //可有条件的引用,报错不会终止应用,引用的文件处理多次//include_once 'test_base.php'; //可有条件的引用,报错不会终止应用,引用的文件处理多次但只显示一次//数据库的测试$hostname = '192.168.1.6'; /*数据库服务器访问地址*/$username = 'root'; /*数据库用户帐号*/$password = 'root'; /*数据库密码*/$database = 'phptest'; /*数据库名称*/$databaseCharset = 'GBK'; /*数据库编码,防止插入中文乱码和报错*///获取请求信息$actionSubmit = $_REQUEST['submit'];$reqTheType = $_REQUEST['theType'];if($reqTheType == null || $reqTheType == '') {	$reqTheType = '1';}echo '请求信息:'.$actionSubmit."|".$reqTheType.'<br>';if($actionSubmit != null && $actionSubmit != '') {	if($reqTheType == '1') {		testSearch();	}	if($reqTheType == '2') {		testInsert();		testSearch();	}	if($reqTheType == '3') {		testUpdate();		testSearch();	}}/** * 数据库查询 * Enter description here ... */function testSearch() {	echo '查询数据<br>';	global $hostname,$username,$password,$database,$databaseCharset;		$currentConn = null;	$currentConn = mysql_connect ( $hostname, $username, $password );	mysql_select_db ( $database );	mysql_query("set names charset ".$databaseCharset);	mysql_query("set names ".$databaseCharset);	$result = mysql_query ( "select * from e_user" ); //查询动作返回的是result结果集	while ( $row = mysql_fetch_object ( $result ) ) {		echo $row->uri . "\t" . ($row->username) . "<br>";	}	mysql_free_result ( $result );	mysql_close ( $currentConn );}/** * 数据库数据添加 * Enter description here ... */function testInsert() {	global $hostname,$username,$password,$database,$databaseCharset;	$insertSql = "insert into e_user(uri,username,password) values";	$insertSql .= "(";	$insertSql .= "'".generateId()."','测试用户','123456'";	$insertSql .= ")";	$currentConn = null;	$currentConn = mysql_connect ( $hostname, $username, $password );	mysql_select_db ( $database );	mysql_query("set names charset ".$databaseCharset);	mysql_query("set names ".$databaseCharset);	echo '添加数据'.$insertSql.'<br>';	$result = mysql_query($insertSql); //插入动作返回的是boolean	if(!$result) {		die('Error: ' . mysql_error());	}	mysql_close ( $currentConn );}/** * 数据库修改 * Enter description here ... */function testUpdate() {	global $hostname,$username,$password,$database,$databaseCharset;	$updateSql = "update e_user";	$updateSql .= " set username='修改后的用户名称' where uri = '001'";	$currentConn = null;	$currentConn = mysql_connect ( $hostname, $username, $password );	mysql_select_db ( $database );	mysql_query("set names charset ".$databaseCharset);	mysql_query("set names ".$databaseCharset);	echo '修改数据'.$updateSql.'<br>';	$result = mysql_query($updateSql); //插入动作返回的是boolean	if(!$result) {		die('Error: ' . mysql_error());	}	mysql_close ( $currentConn );}/** * 自动生成ID号 * @param unknown_type $count */function generateId($count = 6) {	$resultId = '';	for($i=0;$i
Copy after login
checked="checked" } ?>/>查询数据测试 checked="checked" } ?>/>添加数据测试checked="checked" } ?>/>修改数据测试


面向对象编程:
<?php //基础的抽象用户类abstract class BaseUser {	protected $flag = 0;	abstract function showInfo();}//接口类interface Module {	function start();	function stop();}//测试PHP类和对象class MyUser extends BaseUser implements Module {	/*成员变量*/	private $uri = '';	private $type = '';	protected $username = '';	public $password = '';		/*静态变量*/	const USER_TYPE_NORMAL = "normal";		/*构造函数*/	function __construct($uri = '',$username = '', $password = '') {		$this->uri = $uri;		$this->username = $username;		$this->password = $password;		$this->flag = '100';		$this->type = self::USER_TYPE_NORMAL;	}		/*测试静态函数的处理*/	static function testStatic() {		//$this->username = 'static'; //该方法是错误的,静态方法中只能操作静态变量		return self::USER_TYPE_NORMAL;	}		/*get set 方法用于管理内部的字段属性*/	public function getUri() {		return $this->uri;	}	public function getUsername() {		return $this->username;	}	public function getPassword() {		return $this->password;	}	public function setUri($uri) {		$this->uri = $uri;	}	public function setUsername($username) {		$this->username = $username;	}	public function setPassword($password) {		$this->password = $password;	}	public function getType() {		return $this->type;	}	public function setType($type) {		$this->type = $type;	}			/*实现底层的抽象方法*/	function showInfo() {		echo '我是MyUser对象.';	}		//实现接口方法	public function start() {		echo '启动MyUser对象....';	}		//实现接口方法	public function stop() {		echo '停止MyUser对象....';		}}//扩展自MyUser的类class MyExtendUser extends MyUser implements Module {		/*覆盖父类的构造函数*/	function __construct($uri = '',$username = '', $password = '') {		//调用父类的构造函数		parent::__construct($uri,$username,$password);				//实现自己的一些初始化动作		$this->flag = '200';	}		/*覆盖父类的getUsername方法*/	public function getUsername() {		return '继承自MyUser,'.$this->username;	}		//实现接口方法	public function start() {		echo '启动MyExtendUser对象....';	}		//实现接口方法	public function stop() {		echo '停止MyExtendUser对象....';		}}//测试用户对象$theUserObj = new MyUser('001','测试用户1','123');echo '用户名称:'.$theUserObj->getUsername().'<br>';print_r($theUserObj);echo '<br>';echo '测试静态函数1:'.$theUserObj->testStatic().'<br>';echo '测试静态函数2:'.MyUser::testStatic().'<br>';echo '测试实现的接口:';$theUserObj->start();echo '<br>';//测试继承$theUserObj2 = new MyExtendUser('002','测试用户2','123');echo '用户名称2(继承):'.$theUserObj2->getUsername().'<br>';print_r($theUserObj2);echo '<br>';echo '测试实现的接口2:';$theUserObj2->start();echo '<br>';?>
Copy after login

Statement of this Website
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

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

Five selected Go language open source projects to take you to explore the technology world Five selected Go language open source projects to take you to explore the technology world Jan 30, 2024 am 09:08 AM

In today's era of rapid technological development, programming languages ​​are springing up like mushrooms after a rain. One of the languages ​​that has attracted much attention is the Go language, which is loved by many developers for its simplicity, efficiency, concurrency safety and other features. The Go language is known for its strong ecosystem with many excellent open source projects. This article will introduce five selected Go language open source projects and lead readers to explore the world of Go language open source projects. KubernetesKubernetes is an open source container orchestration engine for automated

Go language development essentials: 5 popular framework recommendations Go language development essentials: 5 popular framework recommendations Mar 24, 2024 pm 01:15 PM

&quot;Go Language Development Essentials: 5 Popular Framework Recommendations&quot; As a fast and efficient programming language, Go language is favored by more and more developers. In order to improve development efficiency and optimize code structure, many developers choose to use frameworks to quickly build applications. In the world of Go language, there are many excellent frameworks to choose from. This article will introduce 5 popular Go language frameworks and provide specific code examples to help readers better understand and use these frameworks. 1.GinGin is a lightweight web framework with fast

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

Detailed explanation of the role and usage of the echo keyword in PHP Detailed explanation of the role and usage of the echo keyword in PHP Jun 28, 2023 pm 08:12 PM

Detailed explanation of the role and usage of the echo keyword in PHP PHP is a widely used server-side scripting language, which is widely used in web development. The echo keyword is a method used to output content in PHP. This article will introduce in detail the function and use of the echo keyword. Function: The main function of the echo keyword is to output content to the browser. In web development, we need to dynamically present data to the front-end page. At this time, we can use the echo keyword to output the data to the page. e

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

See all articles