【学习笔记】PHP基础

输出

  • echo “< h1>hello world< /h1>”;
  • echo("< h1>hello world< /h1>");
  • print_r("< h1>hello world< /h1>");
  • var_dump(100); // int(100)
  • var_dump(“hello”); // string(5) “hello”

变量定义

  • 变量以$符号开始,后面跟着变量的名称
  • 变量名必须以字母或者下划线字符开始
  • 变量名只能包含字母数字字符以及下划线
  • 变量名不能包含空格
  • 变量名是区分大小写的
<?php
$str = "hello";
print $str."world";
print "{$str} world";
?>

分支语句

<?php
$isTrue = true;
if (isTrue) {
	echo "True";
} else {
	echo "False";
}

$num = 1;
switch (num) {
	case 1:
		echo "1";
		break;
	case 2:
		echo "2";
		break;
	default:
		break;
}

for ($i = 0; $i < 5; $i++) {
	echo $i;
}
?>

函数

<?php
function print() {
	print "Hello world<br/>";
}
print();
?>

数组

<?php
	// 普通数组
 	$color = array("red", "blue", "green");
 	var_dump($color);
 	echo $color[1];

	for($i=0;$i < count($color);$i++) {
		echo "$color[i]<br>";
	}

	// 关联数组
	$arr = array("zhangsan" => "张三", "lisi" => "李四", "wangwu" => "王五");
	var_dump($arr); // array(3){["zhangsan"]=>string(6) "张三" ["lisi"]=>string(6) "李四" ["wangwu"]=>string(6) "王五"}
	foreach($arr as $key => $value) {
		echo "{$key}:{$value}"; // zhangsan:张三 lisi:李四 wangwu:王五
	}

	// 二维数组
	$arr2 = array(array("name" => "张三", "math" => 100, "english" => 95), 
				  array("name" => "李四", "math" => 92, "english" => 83), 
				  array("name" => "王五", "math" => 80, "english" => 75)
				  );

	for($i = 0; $i < 3; $i++) {
		foreach($arr2[$i] as $key => $value) {
			echo "{$key}:{$value} ";
		}
		echo "<br>";
	}
?>

数组函数

在这里插入图片描述

字符串函数

在这里插入图片描述

时间函数

在这里插入图片描述

数据传输格式

  • xml
    优点:
    • 数据种类丰富
    • 传输数据量大
      缺点:
    • 解析麻烦
    • 不适合轻量级数据
  • json(大多数移动端使用)
    优点:
    • 解析容易
    • 适合轻量级数据
      缺点:
    • 数据种类比较少
    • 传输数据量小

AJAX

AJAX:异步的JavaScript和XML
AJAX是前后端数据的搬运工,可以异步执行

  • 同步:阻塞,当前程序运行必须等前一个程序运行结束才能运行
  • 异步:非阻塞,当前程序运行与前一个程序无关

在这里插入图片描述

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Test</title>
		<script>
			window.onload = function() {
				var oBtn = document.getElementById("btn1");
				var oDiv = document.getElementById("div1");
				oBtn.onclick = function() {
					var xhr = XMLHttpRequest(); // 创建ajax对象
					xhr.open("GET", "1.txt", true);  // true为异步
					xhr.send();
					xhr.onreadystatechange = function() {
						if (xhr.readyState == 4) {
							if (xhr.status == 200) {
								oDiv.innerHTML = xhr.responseText;
							} else {
								alert(xhr.status);
							}
						}
					}
				}
			}
		</script>
	</head>
	<body>
		<button type="button" id="btn1">下载数据</button>
		<div id="div1" style="width: 100px; height: 50px; border: 1px solid black; margin-top: 5px;"></div>
	</body>
</html>

get和post提交

  • get提交
    直接在url后插入数据 http://localhost/1.php?username=abc&password=123
    优点:简单
    缺点:不安全;数据量有上限
  • post提交
    url不会显示数据 http://localhost/1.php
    优点:安全;理论上没有上限
    缺点:底层实现比get复杂
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Test</title>
	</head>
	<body>
		<!-- <form action="1.php" method="get"> -->
		<form action="1.php" method="post" enctype="application/x-www-form-urlencoded">
			<input type="text" name="username" placeholder="用户名" />
			<input type="password" name="password" placeholder="密码" />
			<input type="submit" value="提交"/>
		</form>
	</body>
</html>
<?php
	header(content-type:text/html;charset="utf-8");
	
	// $username = $_GET["username"];
	// $password = $_GET["password"];
	$username = $_POST["username"];
	$password = $_POST["password"];
	echo "用户名为{$username},密码为{$password}";
?>
var xhr = null;
try {
	xhr = new XMLHttpRequest();
} catch(error) {
	xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

// get参数直接在url后面加参数
xhr.open("GET", "1.php?username=abc&password=123", true);
xhr.send();

/* post 提交
xhr.open("POST", "1.php", true);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send("username=abc&password=123");
*/

xhr.onreadystatechange = function() {
	if (xhr.readyState == 4) {
		if (xhr.status == 200) {
			alert(xhr.responseText);
		} else {
			alert(xhr.status);
		}
	}
}

json

var arr = [100, true, "hello"];
var str = JSON.stringify(arr); // 数组转字符串
var arr1 = JSON.parse(str); // 字符串转数组

php中处理json

$arr = array('username' => 'abc', 'password' = > '123');
$str = json_encode($arr); // 数组转字符串
$arr2 = json_decode($str); // 字符串转数组

php 连接 mysql

<?php
	$link = mysql_connect("localhost", "root", "123456");
	if (!link) {
		echo "连接失败";
		exit;
	}

	mysql_set_charset("utf8");
	mysql_select_db("php");
	$sql = "SELECT * FROM students";
	$res = mysql_query($sql);

	echo "<table border='1'>";
	echo "<tr><th>姓名</th><th>成绩</th></tr>";
	while($row = mysql_fetch_assoc($res)) {
		echo "<tr><td>{$row['name']}</td><td>{$row['score']}</td></tr>";
	}
	echo "</table>";
	
	mysql_close($link);
?>

跨源请求

AJAX只能下载同源的数据,不能下载跨源的数据
同源:同协议、同域名、同端口号
跨源的方式:

  • 修改ajax同源协议(不建议)
  • 委托php文件进行跨源
  • JSONP跨域

JSONP跨源步骤

  1. 先声明一个有形参的函数,对这个参数做后续处理
  2. 在需要下载数据时,动态创建script标签,将标签的src设置成要下载的数据的url
  3. 当script插入到页面时,会调用封装好的函数,将数据传至页面
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Test</title>
		<style type="text/css">
			#div0 {text-align: center; margin: 10px auto; margin-top: 50px;}
			#div0 img {width: 250px;}
			#div1 {width: 520px; margin: 10px auto;}
			#input1 {width: 400px; height: 30px; display: inline-block;}
			#input2 {width: 100px; height: 36px; display: inline-block; background-color: royalblue; color: white; border: 0;}
			#ul1 {list-style: none; width: 402px; border: 1px solid black; padding: 0; margin: 0; display: none;}
			#ul1 li a {text-decoration: none; color: black; line-height: 20px; padding: 5px; display: block;}
			#ul1 li a:hover {background-color: orange; color: white;}
		</style>
		<script type="text/javascript">
			function download(data) {
				var arr = data.s;
				var oUl = document.getElementById("ul1");
				oUl.innerHTML = "";
				oUl.style.display = "block";
				
				for (var i = 0; i < arr.length; i++) {
					var oLi = document.createElement("li");
					var oA = document.createElement("a");
					oA.innerHTML = arr[i];
					oA.href = `http://www.baidu.com/s?wd=${arr[i]}`;
					oLi.appendChild(oA);
					oUl.appendChild(oLi);
				}
			}
		</script>
		<script type="text/javascript">
			window.onload = function() {
				var oInput = document.getElementById("input1");
				var oUl = document.getElementById("ul1");
				
				oInput.onkeyup = function() {
					var oValue = this.value;
					if(!oValue) {
						oUl.style.display = "none";
					} else {
						var oScript = document.createElement("script");
						oScript.src = `http://suggestion.baidu.com/su?wd=${this.value}&cb=download`;
						document.body.appendChild(oScript);
					}
				}
			}
		</script>
	</head>
	<body>
		<div id="div0">
			<img src="https://www.baidu.com/img/flexible/logo/pc/result@2.png" >
		</div>
		<div id="div1">
			<input type="text" id="input1" />
			<input type="submit" id="input2" value="百度一下" />
			<ul id="ul1">
			</ul>
		</div>
	</body>
</html>

在这里插入图片描述

cookie

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Test</title>
		<script type="text/javascript">
			window.onload = function() {
				var oDiv = document.getElementById('div1');
				setCookie('name', 'Tom', {expires: 7});
				oDiv.innerHTML = getCookie('name');
				
				var oBtn = document.getElementById('remove');
				oBtn.onclick = function() {
					removeCookie('name');
					removeCookie('age');
					oDiv.innerHTML = getCookie('name');
				}
			}
			
			function setCookie(name, value, {expires, path, domain, secure}) {
				var cookieStr = encodeURIComponent(name) + "=" + encodeURIComponent(value);
				if (expires) {
					cookieStr += ";expires=" + getDateAfter(expires);
				}
				if (path) {
					cookieStr += ";path=" + path;
				}
				if (domain) {
					cookieStr += ";domain=" + domain;
				}
				if (secure) {
					cookieStr += ";secure";
				}
				document.cookie = cookieStr;
			}
			
			function getCookie(name) {
				var cookieStr = decodeURIComponent(document.cookie);
				var start = cookieStr.indexOf(name + '=');
				if (start == -1) {
					return null;
				} else {
					var end = cookieStr.indexOf(';', start);
					if (end == -1) {
						end = cookieStr.length;
					}
					
					var str = cookieStr.substring(start, end);
					return str.split('=')[1];
				}
			}
			
			function removeCookie(name) {
				document.cookie = encodeURIComponent(name) + "=;expires=" + new Date(0);
			}
			
			function getDateAfter(n) {
				var d = new Date();
				var day = d.getDate();
				d.setDate(n + day);
				return d
			}
		</script>
	</head>
	<body>
		<button id="remove">remove</button>
		<div id="div1">
		</div>
	</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值