当前位置:网站首页>Introduction to PHP (self-study notes)

Introduction to PHP (self-study notes)

2022-08-02 03:56:00 Stealth rookie

目录

PHP能做什么?

PHP基础语法

函数

变量

常量

注释

数据类型

运算符

算术运算符

赋值运算符

PHP 比较运算符 

 PHP 逻辑运算符

PHP 数组运算符

PHP流程控制

IF语句

Switch语句

While循环

For循环

魔术常量

__LINE__

__FILE__

__DIR__

__FUNCTION__

__CLASS__

__TRAIT__

__METHOD__

__NAMESPACE__

PHP面向对象

PHP正则表达式

PHP文件上传

PHP会话管理和控制 

 Session

PHP中使用Mysqli与MySQL交互

1.建立、关闭与Mysql服务器的连接

2.执行SQL语句

3.Prepared statements mechanism

 4.创建、插入、更新、过滤、排序、删除


PHP能做什么?

•Can be generated quickly dynamicHTML页面
•Can return to the front to the various types of data
•Can be efficient and safe processing form data
•Safe to operate the file on the server
•Can control and client session( Cookie/Session】
•To authorize the user behavior control
•Can be efficient and safe operating various types of database
•通过扩展,可以实现加密,Other functions such as compression
•Can provide the interface data,包括:小程序、APP、等其他语言

PHP基础语法

PHP 脚本可以放在文档中的任何位置.PHP 脚本以 <?php 开始,以 ?> 结束.

在 PHP 中有两个基本的输出方式: echo 和 print.

函数

创建php函数

函数是通过调用函数来执行的.

<?php function functionName() 
{
    // 要执行的代码 
} 
?>
#如需让函数返回一个值,使用 return 语句.

变量

PHP 变量规则:

  • 变量以 $ 符号开始,后面跟着变量的名称
  • 变量名必须以字母或者下划线字符开始
  • 变量名只能包含字母、数字以及下划线(A-z、0-9 和 _ )
  • 变量名不能包含空格
  • 变量名是区分大小写的($y 和 $Y 是两个不同的变量)

变量的作用域是脚本中变量可被引用和使用的部分,PHP 中有四种不同的变量作用域:

序号作用域描述
1local局部作用域
2global全局作用域
3static静态作用域
4parameter函数参数作用域

常量

 常量值被定义后,在脚本的其他任何地方都不能被改变.

一个常量由英文字母、下划线、和数字组成,但数字不能作为首字母出现. (常量名不需要加 $ 修饰符).

注意:默认是全局变量,常量在整个脚本中都可以使用.

设置常量,使用 define() 函数,函数语法如下:

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )

该函数有三个参数:

  • name:必选参数,常量名称,即标志符.
  • value:必选参数,常量的值.
  • case_insensitive :可选参数,如果设置为 TRUE,该常量则大小写不敏感.默认是大小写敏感的.

注释

<?php
// 这是 PHP 单行注释

/*
这是
PHP 多行
注释
*/
?>

数据类型

PHP 支持以下几种数据类型:

  • String(字符串):一个字符串是一串字符的序列,就像 "Hello world!".
  • Integer(整型):整数
  • Float(浮点型):浮点数是带小数部分的数字,或是指数形式.
  • Boolean(布尔型):布尔型可以是 TRUE 或 FALSE.
  • Array(数组):数组可以在一个变量中存储多个值.$cars=array("Volvo","BMW","Toyota");
  • Object(对象):对象数据类型也可以用于存储数据.必须使用class关键字声明类对象.类是可以包含属性和方法的结构.Data types defined in the class,然后在实例化的类中使用数据类型
  • NULL(空值):NULL 值表示变量没有值.Indicate whether a variable is null values. 同样可用于数据空值和NULL值的区别.可以通过设置变量值为 NULL 来清空变量数据.
  • Resource(资源类型):

    PHP 资源 resource 是一种特殊变量,保存了到外部资源的一个引用.常见资源数据类型有打开文件、数据库连接、图形画布区域等.由于资源类型变量保存有为打开文件、数据库连接、图形画布区域等的特殊句柄,因此将其它类型的值转换为资源没有意义.get_resource_type() 函数可以返回资源(resource)类型:

    get_resource_type(resource $handle): string

运算符

算术运算符

运算符名称描述
x + yx 和 y 的和
x - yx 和 y 的差
x * yx 和 y 的积
x / yx 和 y 的商
x % y模(除法的余数)x 除以 y 的余数
-x设置负数取 x 的相反符号
~x取反

x 取反,按二进制位进行"取反"运算.运算规则:~1=-2; ~0=-1;

a . b并置连接两个字符串

赋值运算符

运算符等同于描述
x = yx = y左操作数被设置为右侧表达式的值
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y模(除法的余数)
a .= ba = a . b连接两个字符串

PHP 比较运算符 

运算符名称描述
x == y等于如果 x 等于 y,则返回 true
x === y绝对等于如果 x 等于 y,且它们类型相同,则返回 true
x != y不等于如果 x 不等于 y,则返回 true
x <> y不等于如果 x 不等于 y,则返回 true
x !== y不绝对等于如果 x 不等于 y,或它们类型不相同,则返回 true
x > y大于如果 x 大于 y,则返回 true
x < y小于如果 x 小于 y,则返回 true
x >= y大于等于如果 x 大于或者等于 y,则返回 true
x <= y小于等于如果 x 小于或者等于 y,则返回 true

 PHP 逻辑运算符

运算符名称描述
x and y如果 x 和 y 都为 true,则返回 true
x or y如果 x 和 y 至少有一个为 true,则返回 true
x xor y异或如果 x 和 y 有且仅有一个为 true,则返回 true
x && y如果 x 和 y 都为 true,则返回 true
x || y如果 x 和 y 至少有一个为 true,则返回 true
! x如果 x 不为 true,则返回 true

PHP 数组运算符

运算符名称描述
x + y集合x 和 y 的集合
x == y相等如果 x 和 y 具有相同的键/值对,则返回 true
x === y恒等如果 x 和 y 具有相同的键/值对,且顺序相同类型相同,则返回 true
x != y不相等如果 x 不等于 y,则返回 true
x <> y不相等如果 x 不等于 y,则返回 true
x !== y不恒等如果 x 不等于 y,则返回 true

PHP流程控制

IF语句

PHP 中,提供了下列条件语句:

  • if 语句 - 在条件成立时执行代码
  • if...else 语句 - 在条件成立时执行一块代码,条件不成立时执行另一块代码
  • if...elseif....else 语句 - 在若干条件之一成立时执行一个代码块
  • switch 语句 - 在若干条件之一成立时执行一个代码块
# if 语句用于仅当指定条件成立时执行代码.

if (条件)
{
    条件成立时要执行的代码;
}
#在若干条件之一成立时执行一个代码块,请使用 if....elseif...else 语句..

if (条件)
{
    if 条件成立时执行的代码;
}
elseif (条件)
{
    elseif 条件成立时执行的代码;
}
else
{
    条件不成立时执行的代码;
}

Switch语句

switch 语句用于根据多个不同条件执行不同动作.Want to one of several blocks of code selectively perform,就使用 switch 语句. 

#示例
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
    echo "你喜欢的颜色是红色!";
    break;
case "blue":
    echo "你喜欢的颜色是蓝色!";
    break;
case "green":
    echo "你喜欢的颜色是绿色!";
    break;
default:
    echo "你喜欢的颜色不是 红, 蓝, 或绿色!";
}
?>

While循环

在 PHP 中,提供了下列循环语句:

  • while - 只要指定的条件成立,则循环执行代码块
  • do...while - 首先执行一次代码块,然后在指定的条件成立时重复这个循环

 while 循环将重复执行代码块,直到指定的条件不成立.

while (条件)
{
    要执行的代码;
}

do...while 语句会至少执行一次代码,然后检查条件,只要条件成立,就会重复进行循环. 

do
{
    要执行的代码;
}
while (条件);

For循环

  • for - 循环执行代码块指定的次数
  • foreach - 根据数组中每个元素来循环代码块

 for 循环用于您预先知道脚本需要运行的次数的情况.

for (初始值; 条件; 增量)
{
    要执行的代码;
}

参数:

    初始值:主要是初始化一个变量值,用于设置一个计数器(但可以是任何在循环的开始被执行一次的代码).
    条件:循环执行的限制条件.如果为 TRUE,则循环继续.如果为 FALSE,则循环结束.
    增量:主要用于递增计数器(但可以是任何在循环的结束被执行的代码).

注释:上面的初始值和增量参数可为空,或者有多个表达式(用逗号分隔).

 foreach 循环用于遍历数组.

foreach ($array as $value)
{
    要执行代码;
}

魔术常量

 A lot of constants are defined by different extensions library,只有在加载了这些扩展库时才会出现,或者动态加载后,或者在编译时已经包括进去了.

有八个魔术常量它们的值随着它们在代码中的位置改变而改变.

__LINE__

文件中的当前行号

<?php 
    echo '这是第 " ' . __LINE__ . ' " 行';   #这是第 “ 2 ” 行
?>

__FILE__

文件的完整路径和文件名.如果用在被包含文件中,则返回被包含的文件名.

<?php
echo '该文件位于 " '  . __FILE__ . ' " ';
?

#该文件位于 “ E:\wamp\www\test\index.php ”

__DIR__

文件所在的目录.如果用在被包括文件中,则返回被包括的文件所在的目录.

它等价于 dirname(__FILE__).除非是根目录,否则目录中名不包括末尾的斜杠.

<?php
echo '该文件位于 " '  . __DIR__ . ' " ';
?>

#该文件位于 “ E:\wamp\www\test ”

__FUNCTION__

Function name to return to the function is defined when the name of the(区分大小写).

<?php
function test() {
    echo  '函数名为:' . __FUNCTION__ ;
}
test();
?>

#函数名为:test

__CLASS__

The name of the class to return to the class defined in the name of the(区分大小写).

<?php
class test {
    function _print() {
        echo '类名为:'  . __CLASS__ . "<br>";
        echo  '函数名为:' . __FUNCTION__ ;
    }
}
$t = new test();
$t->_print();
?>

#类名为:test
#函数名为:_print

__TRAIT__

A method of code reuse,称为 traits.Trait 名包括其被声明的作用区域

<?php
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}
 
trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}
 
class MyHelloWorld extends Base {
    use SayWorld;
}
 
$o = new MyHelloWorld();
$o->sayHello();
?>

#Hello World!

__METHOD__

类的方法名.返回该方法被定义时的名字(区分大小写).

<?php
function test() {
    echo  '函数名为:' . __METHOD__ ;
}
test();
?>

#函数名为:test

__NAMESPACE__

当前命名空间的名称(区分大小写).

<?php
namespace MyProject;
 
echo '命名空间为:"', __NAMESPACE__, '"'; // 输出 "MyProject"
?>

#命名空间为:"MyProject"

PHP面向对象

#PHP 类定义
<?php
class phpClass {
  var $var1;
  var $var2 = "constant string";
  
  function myfunc ($arg1, $arg2) {
     [..]
  }
  [..]
}
?>

#PHP 中创建对象
#类创建后,我们可以使用 new 运算符来实例化该类的对象:
$runoob = new phpClass;

#在实例化对象后,我们可以使用该对象调用成员方法,该对象的成员方法只能操作该对象的成员变量:

解析如下:

  • 类使用 class 关键字后加上类名定义.

  • 类名后的一对大括号({})内可以定义变量和方法.

  • 类的变量使用 var 来声明, 变量也可以初始化值.

  • 函数定义类似 PHP 函数的定义,但函数只能通过该类及其实例化的对象访问.

PHP正则表达式

PCRE部分函数

 运算符优先级

相同优先级的从左到右进行运算,不同优先级的运算先高后低.下表从最高到最低说明了各种正则表达式运算符的优先级顺序:

运算符描述
\转义符
(), (?:), (?=), []圆括号和方括号
*, +, ?, {n}, {n,}, {n,m}限定符
^, $, \任何元字符、任何字符定位点和序列(即:位置和顺序)
|替换,"或"操作
字符具有高于替换运算符的优先级,使得"m|food"匹配"m"或"food".若要匹配"mood"或"food",请使用括号创建子表达式,从而产生"(m|f)ood".

PHP文件上传

文件上传表单 

<html>
<head>
<meta charset="utf-8">
<title>文件上传</title>
</head>
<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
    <label for="file">文件名:</label>
    <input type="file" name="file" id="file"><br>
    <input type="submit" name="submit" value="提交">
</form>

</body>
</html>

 上传脚本

<?php
// 允许上传的图片后缀
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]); //explode() 函数使用一个字符串分割另一个字符串,
                                                 并返回由字符串组成的数组.
$extension = end($temp);   // 获取文件后缀名  (end()输出数组中的当前元素和最后一个元素的值)
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 204800)    // 小于 200 kb
&& in_array($extension, $allowedExts)) //in_array() 函数搜索数组中是否存在指定的值.
{
    if ($_FILES["file"]["error"] > 0)
    {
        echo "错误:: " . $_FILES["file"]["error"] . "<br>";
    }
    else
    {
        echo "上传文件名: " . $_FILES["file"]["name"] . "<br>";
        echo "文件类型: " . $_FILES["file"]["type"] . "<br>";
        echo "文件大小: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "文件临时存储的位置: " . $_FILES["file"]["tmp_name"] . "<br>";
        
        // 判断当前目录下的 upload 目录是否存在该文件
        // 如果没有 upload 目录,你需要创建它,upload 目录权限为 777
        if (file_exists("upload/" . $_FILES["file"]["name"]))
        {
            echo $_FILES["file"]["name"] . " 文件已经存在. ";
        }
        else
        {
            // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);

//move_uploaded_file() 函数把上传的文件移动到新位置.move_uploaded_file(file,newloc) file 规定 
  要移动的文件.newloc 规定文件的新位置.

            echo "文件存储在: " . "upload/" . $_FILES["file"]["name"];
        }
    }
}
else
{
    echo "非法的文件格式";
}
?>

PHP会话管理和控制 

cookie 常用于识别用户.cookie 是一种服务器留在用户计算机上的小文件.每当同一台计算机通过浏览器请求页面时,这台计算机将会发送 cookie.通过 PHP,能够创建并取回 cookie 的值.

流程:

1.It is the first time you visit a web page,The server will give the user to create aCookie

2.Next time to access the web page,Will be for the user to createCookie发给服务端,The server with thisCookie做对比,若有该Cookie则放行 

1.向客户端电脑中设置Cookie

        setcookie();

2.On the server side to readcookie的内容

        $_COOKIE

3.将多维数组应用于Cookie中

4.删除Cookie

        setcookie("member",' ',time()-1);

注释:setcookie() 函数必须位于 <html> 标签之前.

setcookie(name, value, expire, path, domain);
<?php
setcookie("name", "小明", time()+3600);  #time()+3600是有效期,单位是秒
?>

<html>
.....

#Another way to set up cookie 的过期时间

<?php
$expire=time()+60*60*24*30;
setcookie("name", "小明", $expire);
?>

<html>
.....
#Put the data content in an array
<?php
header('Content-type:text/html;charset=utf-8')
setcookie('member[name]','小明',time()+3600);
setcookie('member[email]','[email protected]',time()+3600);
?>

在服务器上读取Cookie的内容,PHP 的 $_COOKIE 变量用于取回 cookie 的值.

 $_COOKIE 是超全局变量,All files can affect

#这一个php文件,Can get to the other file information
<?php
header('Content-type:text/html;charset=utf-8')
var_dump($_COOKIE);
?>

删除 Cookie

当删除 cookie 时,您应当使过期日期变更为过去的时间点.

<?php
// 设置 cookie 过期时间为过去 1 小时
setcookie("user", "", time()-3600);
?>
-----------------------------------------
<?php
setcookie('member[name]',' ',time()-3600);
setcookie('member[email]',' ',time()-3600);
?>
------------------------------------------
<?php
foreach($_COOKIE['member'] as $ket=>$val){
    setcookie("member[$key]",' ',time()-3600);
}
?>

 Session

Session 的工作机制是:为每个访客创建一个唯一的 id (UID),并基于这个 UID 来存储变量.UID 存储在 cookie 中,或者通过 URL 进行传导. 

(通过在服务器上存储用户信息以便随后使用(比如用户名称、购买商品等).然而,会话信息是临时的,在用户离开网站后将被删除.If you need a permanent storage information,可以把数据存储在数据库中.)

流程:

1.It is the first time you visit the page,服务器会给每一个用户(浏览器)创建一个Seesion对象,The object in aid是唯一的.

2.The user the next visit web page,The server directly match the user'sid,If the user to create aSession对象,则放行 

 1.开启session

        session_start();  #开启一个会话;打开已经存在的会话

2.使用session存储数据

        $_SESSION  #存储和取回 session 变量的正确方法是使用 PHP $_SESSION 变量

3.注销变量与销毁session

注意点:使用setcookie删除cookie的时候,需要与当初设置cookie的时候参数一致

 

PHP中使用Mysqli与MySQL交互

MySQL 是一种在 Web 上使用的数据库系统,A server running on the database system.

1.建立、关闭与Mysql服务器的连接

(1)连接指定的MySQL数据库服务器

        [email protected]_connect($host,$user,$password,$database,$port);

(2)Connection error when the tip

        int mysqli_connect_error(); //返回最后一次连接调用的错误代码

        string mysqli_connect_error(); //返回一个字符串描述的最后一次连接调用的错误代码

(3)设置默认字符编码

        bool mysqli_set_charset(mysql $link,string $charset);

(4)选择特定的数据库

        bool mysqli_select_db(mysql $link,string $dbname);

(5)关闭与mysql服务器的连接

        bool mysqli_close(myslqi $link);

-------------------------------------------------------------------------------------------------------------------------

2.执行SQL语句

1)To perform a databaseSQL语句

1>mixed mysqli_query(mysqli $link,string $query[,int Sresultmode= MYSQU_STORE_RESULT]);

①对于insert,update,deleteWill not return data such asSQL语句,When performing no error will returntrue.

②对于返回数据的SQLStatement execution success will return a result set,可以Using the operating result set object functionTo get data from

③MYSQLI_STORE_RESULT和MYSQLI_USE_RESULT决定了mysqli client和serverTake the result set between the way.MYSQLI_STORE_RESULT:执行SQLWhen extracting the result set is returned to theclient,并分配内存,Stored in the user program in the space,之后mysqli_fetch_array() Equivalent to fetch the data from local;而MYSQLI_USE_RESULT方式下,mysqli_fetch_array()每次都要向serverRequest a result row.

MYSQLI_USE_RESULT:执行SQLNot fromserverThe result set back

2>bool mysqli_real_query(mysqli Slink,string Squery);

Can also use this function to perform a databaseSQL语句,返回结果为布尔值,不返回结果集.

If you want to get the result set can be usedmysqli_store_result()获取结果集对象.

3>如果在执行SQL语句的时候发生错误,The above two functions will returnfalse,And you can use the following function to deal with the reason for the error

int mysqli_error(mysqli $link);

string mysqli_error(mysqli $link);

2)操作结果集对象的函数

1>Common function of analytical data from the result set object

①以索引数组的方式获取一条记录的数据

mixed mysqli_fetch_row(mysqli_result $result);

Under repeated use for a record data

②以关联数组的方式获取一条记录的数据

array mysqli_fetch_assoc(mysqli_result $result);

Under repeated use for a record data

③以索引数组或关联数组的方式获取一条记录的数据

mixed mysqli_fetch_array(mysqli_result $result [, int Sresulttype = MYSQu_BOTH ] );

Under repeated use for a record data

④以索引数组或关联数组的方式获取全部记录的数据

mixed mysqli_fetch_all(mysqli_result $result[,int $resulttype = MYSQLI_NUM ]);

⑤Returns the result set the next field information

object mysqli_fetch_field(mysqli_result $result);

⑥Returns an array of objects on behalf of the result set fields

array mysqli_fetch_fields(mysqli_result $result);

⑦获取结果中行的数量

int mysqli_num_rows(mysqli_result $result);

注意:如果使用MYSQLI_USE_RESULTPattern must be after get the result set to use this function.

2>Group put memory associated with a result set

The returned result sets that need a lot of memory in the amount of data is very big support,So after operation result set when it is necessary to immediately release the memory associated with a result set,释放之后,The result set is unavailable

void mysqli_free_result(mysqli_result $result);

3)其他常用函数

1>获取前一个Mysql操作的受影响行数

int mysqli_affected_rows(mysqli $link);

2>Returns the last operation automatically generate and useid

mixed mysqli_insert_id(mysqli $link);

3>Escaping is used toSQLStatements of special characters to preventSQL语句出错

(Escape is caused in order to avoid certain special charactersSQL语句出现语法错误,Can let the data warehousing smoothly)

string mysqli_real_escape_string(mysqli $link,string Sescapestr);

4)一次性执行多条SQL语句,多个SQL语句用分号隔开

bool mysqli_multi_query(mysqli $link,string $query);
 

#建立mysql连接-----------------------------------------------------------
<?php
$servername = "localhost"; //mysql服务器主机地址
$username = "username"; //mysql用户名
$password = "password"; //mysql用户密码
 
// 创建连接
$conn = mysqli_connect($servername, $username, $password);
 
// 检测连接
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error()); //Connection error when the tip
}
echo "连接成功";
?>
//设置默认字符编码
mysqli_set_charset($conn,'utf8');
//选择特定的数据库
mysqli_select_db($conn,'myDB')

#执行SQL语句---------------------------------------------------------------

//$query='insert into t1(info) values(“小明,15,qwweeee.com”)'; 插入数据.t1是表,info是列名
//$query='update t1 set info="学生" where id=7';
$query='select * from t1' 
$result=mysqli_query($conn,$query); //To save the data returned as a variable in the,Using the operating result set object function,获得数据
var_dump(mysqli_fetch_row($result)); //Perform a output under a,假如数据有3条,Then use this statement3次
while ($data=mysqli_fetch_row($result)){
    var_dump($data);                 //遍历输出
}
//以关联数组的方式获取一条记录的数据
var_dump(mysqli_fetch_assoc($result)); 

//如果使用MYSQLI_USE_RESULTPattern must be after get all the results can use this function
var_dump(mysqli_num_rows($result));

//Release the memory associated with a result set
mysqli_free_result($result);

//2.(1).2>  mysql_real_query(),Apply to only need to return Boolean values,Determine demand have performed successfully
if(mysql_real_query($conn,$query)){
    $result=mysqli_store_result($conn);
    var_dump(mysqli_fetch_rowa($result));//A time to get a
}

//显示错误原因,这里t2There is no table.
//如果在执行SQL语句的时候发生错误,The above two functions will returnfalse,And you can use the following function to deal with the reason for the error
$query='insert into t2(info) value('小明')';
if(!mysqli_query($conn,$query)){
    var_dump(mysqli_errno($conn));  //错误代号
    var_dump(mysqli_error($conn));  //具体错误原因
} 

#关闭mysql连接--------------------------------------------------------------
//关闭与mysql服务器的连接
mysqli_close($conn);
//Transfer toSQLStatements of special characters to preventSQL语句出错
$str=<<<STRING
dwqdnducd'''''''d.;;.;cd;;;;;..;.//Content to write here
STRING;
$str=mysqli_real_escape_string($conn,$str); //转义
$query="insert into t1(info) values('{$str}')";
//一次性执行多条SQL语句
$query='insert into t1(info) values("小明");insert into t1(info) values("学生");'
var_dump(mysqli_multi_query($conn,$query));

3.Prepared statements mechanism

在编写PHP代码执行SQL语句的时候,In many cases are similar statements,Only the parameters of the individual different,In the presence of the repeat similar statements,提供了一种名为预处理语句的机制,It can be the entire statement only toMySQL服务器发送一次,Only after parameter change,MySQLThe server only need to do an analysis about the structure of statement就够了.It reduces the need to the amount of data transferred,But also improve the statement processing efficiency.

1)Prepare a used to performSQL语句

mysqli_stmt mysqli_prepare(mysqii $link,string $query);

2)Variable as the parameter is bound toprepared语句上

bool mysqli_stmt_bind_param(mysqli_stmt $stmt,string $types,mixed&$var1[,mbxed &$...]);

参数string $types说明:Said behind multiple optional parameter variable's data type,—对应.

i:int类型

d:double或者float类型

s:字符串类型

b:二进制数据类型(BLOB、二进制字符串)

3)执行一个prepared准备好的语句

bool mysqli_stmt_execute( mysqli_stmt $stmt );

4)The query of data binding toPHP变量上

bool mysqli_stmt_bind_result ( mysgli_stmt $stmt , mixed &$var1 [, mixed &$...])

5)从一个preparedStatement to grab the results to the specified variable

bool mysqli_stmt_fetch (mysqli_stmt $stmt );

6)从一个preparedStatement returns a result set metadata,Cooperate with related functions,Can be used to obtain the field information

mysqli_result mysqli_stmt_result_metadata ( mysgli_stmt $stmt)

①mysqli_fetch_field();

①mysqli_fetch_fields();

7)To retrieve a result set

bool mysqli_stmt_store_result ( mysqli_stmt $stmt );

//预处理机制
//准备的sql语句里面使用占位符?,To represent the parameters to change
$query='insert into t1(id,info) values(?,?)';
//准备要执行的SQL语句
$stmt=mysqli_prepare($conn,$query);
#var_dump($stmt);
//为?绑定变量.  i代表整型id对应val1,s代表字符串类型info对应val2
mysqli_stmt_bind_param($stmt,'is',$val1,$val2); 
//赋具体值
$val1=18;
$val2="行不行";
//执行准备好的SQL语句
var_dump(mysqli_stmt_execute($stmt));
//如果是selectSuch statements need concrete results
$query='select * from t1 where id=?';
$stmt=mysql_prepare($conn,$query);
mysqli_stmt_bind_param($stmt,'i',$val1);
$val1=1;
var_dump(mysqli_stmt_execute($stmt));
mysqli_stmt_bind_result($stmt,$id,$info); //绑定结果
mysqli_stmt_fetch($stmt);
echo "{$id}->{$info}<br />"; 
------------------------------------------------------------
$query='select * from t1 where id=? or id=?';        
$stmt=mysql_prepare($conn,$query);
mysqli_stmt_bind_param($stmt,'ii',$val1,$val2);
$val1=1;
$val2=2;
if(mysqli_stmt_execute($stmt)){
    mysqli_stmt_bind_result($stmt,$id,$info);
    //var_dump(mysqli_stmt_fetch($stmt));
    //echo "{$id}->{$info}<br />"; 
    //var_dump(mysqli_stmt_fetch($stmt));
    //echo "{$id}->{$info}<br />"; 
    while(mysqli_stmt_fetch($stmt)){   //循环输出
    echo "{$id}->{$info}<br />";
    }
}
// 6)从一个preparedStatement returns a result set metadata,Cooperate with related functions,Can be used to obtain the field information
if(mysqli_stmt_execute($stmt)){
    $result=mysqli_stmt_fetch_result_metadata($stmt);
    var_dump(mysqli_fetch_field($result));
}
---------------------------------------------------------------
$query='select * from t1 where id<?';        

 4.创建、插入、更新、过滤、排序、删除

<?php
$servername = "localhost";
$username = "username";
$password = "password";
 
// 创建连接
$conn = mysqli_connect($servername, $username, $password);
// 检测连接
if (!$conn) {
    die("连接失败: " . mysqli_connect_error());
}
----------------------------------------------------------------
// 创建数据库
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
    echo "数据库创建成功";
} else {
    echo "Error creating database: " . mysqli_error($conn);
}
-----------------------------------------------------------------
// 使用 sql 创建数据表
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
 
if (mysqli_query($conn, $sql)) {
    echo "数据表 MyGuests 创建成功";
} else {
    echo "创建数据表错误: " . mysqli_error($conn);
}
------------------------------------------------------------------
//插入数据
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
------------------------------------------------------------------
//插入多条数据
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";
------------------------------------------------------------------
//输出数据
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
    echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
------------------------------------------------------------------
//where子句用于过滤记录.
$result = mysqli_query($con,"SELECT * FROM Persons
WHERE FirstName='Peter'");
while($row = mysqli_fetch_array($result))
{
    echo $row['FirstName'] . " " . $row['LastName'];
    echo "<br>";
}
-------------------------------------------------------------------
//ORDER BY 关键词用于对记录集中的数据进行排序.
$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");
while($row = mysqli_fetch_array($result))
{
    echo $row['FirstName'];
    echo " " . $row['LastName'];
    echo " " . $row['Age'];
    echo "<br>";
}
--------------------------------------------------------------------
//UPDATE 语句用于中修改数据库表中的数据.
mysqli_query($con,"UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
--------------------------------------------------------------------
//DELETE 语句用于从数据库表中删除行.
mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");
--------------------------------------------------------------------

mysqli_close($conn);
?>
原网站

版权声明
本文为[Stealth rookie]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208020322316896.html