基本语法
数据类型
String,Integer(整型),Float,Boolean,Array,Object,Null
开头
header('content-type:text/html;charset="utf-8"');
输出函数
echo
echo "<h1>hello</h1>"
print "false";
输出函数中有html代码会自动解析
定义变量
$username = "钢铁侠"
$age = 10;
条件语句
$sum = 2;
if($sum) {
print $sum;
}else{
print "false";
}
循环语句
for($i = 0;$i < 5;$i ++) {
echo $i;
}
函数
function PrintName() {
print "hello word";
}
PrintName();
PrintName();
数组
1.索引数组:下标是数字
$arr = array(1,2,3);
$arr1 = [1,2,3];
var_dump($arr);//访问数组
echo $arr[0];
2.关联数组:下标是字符串
$arr2 = array("第一个" => "shiwu","第二个" => "qwe","第三个" => "asd");
var_dump($arr2);
echo "<br>";
echo $arr2["第一个"];
echo "<br>";
3.全局数组
-
$_GET 接收通过get提交过来的所有数据
-
$_POST 接收通过post提交过来的所有数据
4.数组的长度
count($arr);
5.数组的遍历
第一种就是通过for循环遍历
第二种通过foreach
foreach($arr as $key => $value) {
echo $key."--".$value;
}
字符串
$str = "hello";//""先解析再输出
$str1 = 'hello';//''直接当字符串输出
字符串拼接
<?php
header('content-type:text/html;charset="utf-8');
echo "<h1>hello world 1</h1>";
$name = "taoyuhan";
$age = 12;
echo "我叫做".$name."我今年".$age."岁";
?>
预定义变量
前端传递参数
-
$_GET('变量')
-
$_POST('变量')
PHP连接数据库
(1)创建数据库
语法:Object mysqli_connect("域名","账号","密码","库名","端口号")
端口号如果改了再加上,不改就不用加
示例:
$first = mysqli_connect('localhost','root','','first');
(2)设置编码
语法:
mysqli_query($first,'set names utf8');
(3)编写sql语句
$sql = "insert into userinfo (username,password) values('qwe','999')";
(4)执行sql语句
$result = mysqli_query($first,$sql);
(5)关闭数据库
mysqli_close($first);
完整示例
<?php
//1.创建数据库
$firstDatabase = mysqli_connect('localhost', 'root', '', 'firstconnect');
if ($firstDatabase) {
//2.设置编码
mysqli_query($firstDatabase,'set names utf8');
//3.编写sql语句
$sql = "insert into userinfo (username,password) values('xys','999')";
//4.执行sql语句
$result = mysqli_query($firstDatabase,$sql);
var_dump($result);//bool(true)
}else {
echo '连接失败';
}
//5.关闭数据库
mysqli_close($firstDatabase);
?>
sql语句
-
插入语句
"insert into 表名 (username,password) values('xys','999')"
-
修改语句
"update 表名 set 字段1 = '新值1',... where id = $id"
示例
$sql = "update userinfo set password='8888' where id = 1";
-
删除语句
"delete from 表名 where 条件"
-
查询语句
"select [信息] from [表名] where [查询条件]"
示例
<?php $firstDatabase = mysqli_connect('localhost', 'root', '', 'firstconnect'); if ($firstDatabase) { mysqli_query($firstDatabase,'set names utf8'); //1.查询表里面所有信息 $sql = "select * from userinfo"; //2.查询id = 1的这条数据的所有信息 $sql = "select * from userinfo where id = 2"; //3.查询表里面所有的用户名字 $sql = "select username from userinfo where id = 2"; //4.查询用户密码 $sql = "select username,password from userinfo where id = 2"; //5.查询条件满足多个(或者用or) $sql = "select * from userinfo where username = 'admin' and password = '123456'"; $result = mysqli_query($firstDatabase,$sql); if($result->num_rows > 0){ $arr = mysqli_fetch_all($result,MYSQLI_ASSOC); print_r($arr); }else{ echo '查无信息'; } }else { echo '连接失败'; } mysqli_close($firstDatabase); ?>