Home  >  Article  >  Backend Development  >  The latest summary of 2018PHP interview questions (with answers)

The latest summary of 2018PHP interview questions (with answers)

不言
不言forward
2018-12-12 11:08:0410681browse

This article brings you the latest summary of the 2018 PHP interview questions (with answers). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Related recommendations: "2019 PHP Interview Questions Summary (Collection)"

1. Basics of PHP Frequent Examination

1. What is the difference between PHP, ASP and JSP?

ASP's full name is Active Server Pages. It is a Web server-side development environment based on the Windows platform. It can be used to generate and run dynamic, interactive, and high-performance Web service applications. It only It can be used on Microsoft platforms, but portability is not good. ASP uses scripting languages ​​​​VB Script and JScript (JavaScript) as its own development language. Most of the early domestic websites were developed using it. However, due to Microsoft's overall shift, ASP.NET gave up the ASP Web development model, so it has now been eliminated.
PHP is a cross-platform server-side embedded scripting language. It borrows a lot of syntax from C, Java and Perl languages, and couples PHP's own features to enable Web developers to quickly write dynamically generated pages. It can be embedded in HTML, making it very suitable for Web development, and it supports most current databases. In addition, PHP is completely free. Developers can download it freely from the PHP official site (http://www.php.net) without spending money. Moreover, developers can obtain the source code without restrictions, and can even add the features they need, resulting in high development efficiency and low cost.
JSP is a network programming language launched by Sun. It runs cross-platform, has high security and high operating efficiency. Its development language is mainly based on Java.
ASP, JSP, and PHP all provide the ability to mix some kind of program code in HTML code and interpret it for execution by the language engine. However, JSP code is compiled into Servlet and interpreted and executed by the Java virtual machine. This compilation operation is only used for Occurs when the JSP page is requested for the first time. In ASP, PHP, and JSP environments, HTML code is mainly responsible for describing the display style of information, while program code is used to describe processing logic. Ordinary HTML pages only rely on the Web server, while ASP, PHP, and JSP pages require additional language engines to analyze and execute program code. The execution results of the program code are re-embedded in the HTML code and then sent to the browser together. ASP, PHP, and JSP are all Web server-oriented technologies, and the client browser does not require any additional software support.

2. In PHP, the difference between strings surrounded by single quotes and double quotes is ( ).

A. Single quotes parse escape characters such as rt, while double quotes do not parse
B. Double quotes are fast, single quotes are slow
C. Single quotes are fast, double quotes are slow                                      
D. Double quotes parse variables starting with $, while single quotes do not parse
Reference answer: D.
Analysis: Double quotes can parse variables and escape characters starting with the $ symbol, while single quotes do not parse or escape characters. Therefore, option A is wrong and option D is correct.
For options B and C, since the question clearly states that the quotes contain strings, there is no need to parse the variables. In this case, the efficiency of double quotes and single quotes is the same. Both options B and C are incorrect.

3. What is the difference between object-oriented and process-oriented?

Object-oriented is one of the mainstream methods of today's software development methods. It puts data and operations on data together as an interdependent whole, that is, an object. Abstract the common features of similar objects, that is, classes. Most of the data in the class can only be processed by the methods of this class. The class relates to the outside world through a simple external interface, and objects communicate through messages. The program flow is determined by the user during use. For example, from an abstract perspective, humans have special names such as height, weight, age, blood type, etc. Human beings can work, walk upright, eat, and use their own minds to create tools. Human beings are just an abstraction. It is a non-existent entity, but all objects that have the attributes and methods of the human group are called people. This object person is an entity that actually exists, and everyone is an object of the human group.
Process-oriented is an event-centered development method, which is executed sequentially from top to bottom and gradually refined. Its program structure is divided into several basic modules according to functions. These modules form a tree structure. The relationship between each module is relatively simple and relatively independent in function. Each module is generally composed of three basic structures: sequence, selection and loop. The specific method of modular implementation is to use subroutines, and the program flow This is decided when writing the program. For example, in backgammon, the process-oriented design idea is to first analyze the steps of the problem: the first step, start the game; the second step, the black stone moves first; the third step, draw the picture; the fourth step, judge the winner or lose; the fifth step, it is the turn White; Step 6, draw the picture; Step 7, determine the winner or lose; Step 8, return to step 2; Step 9, output the final result. Implementing each of the above steps with separate functions is a process-oriented development method.
Specifically, the two mainly differ in the following aspects.
1) The starting point is different. Object-oriented is to use conventional thinking methods to deal with problems in the objective world, emphasizing the direct mapping of the key points of the problem domain to objects and the interfaces between objects. This is not the case with the process-oriented method. It emphasizes the abstraction and modularization of the process. It constructs or handles objective world problems with the process as the center.
2) The hierarchical logical relationships are different. The object-oriented method uses computer logic to simulate the physical existence in the objective world, uses the collection class of objects as the basic unit for processing problems, and makes the computer world as close to the objective world as possible, so that the processing of problems is clearer and more direct, and is oriented to The object method uses the hierarchical structure of classes to reflect the inheritance and development between classes. The basic unit of process-oriented method to deal with problems is a module that can clearly and accurately express the process. The hierarchical structure of the module is used to summarize the relationships and functions between modules or modules, and the problems in the objective world are abstracted into processes that can be processed by computers.
3) The data processing method is different from the control program method. The object-oriented method encapsulates the data and the corresponding code into a whole. In principle, other objects cannot directly modify its data, that is, the modification of the object can only be completed by its own member functions. The control program is activated and activated through "event-driven" Run the program. The process-oriented method processes data directly through the program, and the processing results can be displayed after the processing is completed. In the control program method, the program is called or returned according to the design, and cannot be freely navigated. There are controls, controlled, and calls between each module. with being called.
4) Analysis design and coding conversion methods are different. The object-oriented method is a smooth process throughout the software life cycle between analysis, design and coding. From analysis to design to coding, a consistent model representation is used, that is, a seamless connection is achieved. The process-oriented method emphasizes the transformation between analysis, design and coding according to rules, and achieves a seamless connection between analysis, design and coding throughout the software life cycle.

4. In PHP, the way to customize a class is ( ).

A.        
B.
C.        
D.
Reference answer: B.
Analysis: To define a class, use the class keyword plus the class name to define it. The definition format is: class class name {}. The format for instantiating a class is: $object=new classname();.
[Real Question 11] The function to obtain the name of the class to which the instantiated object belongs is ( ).
A. get_class()                     B. get_object_vars()
C. get_class_methods()             D. get_classname()
Reference answer: A.
Analysis: For option A, the get_class() function is used to return the name of the class of an object. Therefore, option A is correct.
For option B, the get_object_vars() function is used to get the attributes of the given object. Therefore, option B is wrong.
For option C, the get_class_methods() function is used to get the name of the class method. Therefore, option C is incorrect.
For option D, there is no such method in PHP. Therefore, option D is incorrect.

5. Among the following statements about PHP object-oriented, which one is incorrect ( ).

A. To implement an interface, use the implements operator. The class must implement all methods defined in the interface, otherwise a fatal error will be reported
B. The class name can be any legal tag that is not a PHP reserved word, and Chinese characters can also be used as PHP class names
C. If a constructor is defined in a PHP subclass, when creating an object of the subclass, the constructor of its parent class will be implicitly called
D. Serializing an object will save all the variables of the object, but the methods of the object will not be saved. Only the name of the class will be saved.
Reference answer: C.
Analysis: The constructor defined by the subclass will override the constructor of the parent class. If you want the constructor of the subclass to be executed as well as the constructor of the parent class, you must explicitly use parent::__construct(); to call. Therefore, option C is incorrect.

6. In the following description of PHP abstract classes, the wrong one is ( ).
A. Abstract classes in PHP are defined using the abstract keyword
B. A method without a method body is called an abstract method, and the class containing the abstract method must be an abstract class
C. There must be an abstract method in an abstract class, otherwise it is not called an abstract class
D. Abstract classes cannot be instantiated, that is, they cannot be new into objects
Reference answer: C.
Analysis: An abstract class can be an empty class, which means it does not necessarily need to have an abstract method. But abstract methods can only exist in abstract classes. Therefore, option C is incorrect.

7. What is polymorphism?
Polymorphism is an important mechanism for code reuse in object-oriented programming. It means that when the same operation is applied to different objects, there will be different semantics, which will produce different results. For example, in the same " " operation, 3 4 is used to add integers, while "3" "4" implements string concatenation. Generally speaking, there are two ways to implement polymorphism: overwriting and overloading.

8. What is the difference between include and require?
require and include have similar functions: copy all code/text/marks in the specified file to the file using the require or include statement. Usually used in scenarios where data, files or code need to be shared. By putting the code or data that needs to be shared into a separate PHP file, reference it through require or include in the files that need to be used. require() and include() are not real functions, therefore, require() and include() statements can also add parameters directly without parentheses.

9. The output of the following code is ( ).

<?php
    define("x","5"); 
    $x=x+10; 
    echo x; 
?>

A. Error             B. 5 C. 10 D. 15
Reference answer: B.
Analysis: In PHP, the define function is used to define a constant, and the value of the constant cannot be changed after it is set. In this problem, the value of x is always 5. Therefore, option B is correct.

10. How to reference variables?
You can add an & symbol in front of the variable to reference the variable. The reference of the variable is equivalent to giving the variable an alias. The same variable content is accessed through different names, so changing the value of one variable will change the value of the other variable. A variable will also change.

[Real Question 54] There is the following code:

<?php
    $a="hello";
    $b= &$a;
    unset($b);
    $b="world";
    echo $a;
?>

The running result of the program is ( )
A. hello B. world C. NULL D. unset
Reference answer: A.
Analysis: The execution process of this code is shown in the figure below.

1)首先执行$b= &$a后,a和b引用同一个字符串变量“hello”。
2)接着执行unset($b),这个函数可以断开这个引用关系。此时由于a仍然指向字符串“hello”,也就是说,这个字符串仍然被a使用,因此这个字符串不会被回收。
3)接着执行$b="world",此时,b指向一个新的字符串“world”,这并不会影响a的值。因此输出结果为hello。

2、PHP常考进阶
11、请写一个函数验证电子邮件的格式是否正确。
参考答案:

function checkEmail($email)
{
    $pregEmail= "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
    return preg_match($pregEmail,$email);  
}

分析:首尾两个斜杠/是正则表达式的限定符,这是Perl正则的标准,而PHP与Perl有相同的正则的规范。两个斜杠之间表示的是正则内容,后面的i表示忽略大小写。
这个正则表达式表示的含义如下:
1)必须以([0-9A-Za-z\-_\.]+)开头,也就是说,邮件地址以多个字母、数组、“-”或“.”开头。
2)紧接着是字符“@”。
3)然后接着是多个字母或数字的字符串,接着是一个字符“.”,接着是两个或三个字母;然后接下来一部分可有可无的:一个“.”后面跟着两个字母。
4)邮件的结束符是满足3)的字符串。

12、以下可以匹配中国居民身份证号码的正则表达式是(    )。
A.d{15}                    B.d{18}        
C.d                        D.(^d{15}$)|(^\d{18}$)|(^d{17}(d|X|x)$)
参考答案:D。
分析:d表示0~9任意数字。

13、【真题96】 一个函数的参数不能是对变量的引用,除非在php.ini中把(    )设为on。
参考答案:allow_call_time_pass_reference。
分析:在PHP函数调用的时候,基本数据类型默认会使用值传递,而不是引用传递。allow_call_time_pass_reference 选项的作用为是否启用在函数调用时强制参数被按照引用传递。如果把allow_call_time_pass_reference 配置为on,那么在函数调用的时候会默认使用引用传值。但是不推荐使用这种方法,原因是该方法在未来的版本中很可能不再支持。如果想使用引用传递,那么推荐在函数调用的时候显式地使用&进行引用传递。

14、文件读操作
读取文件前,通常会判断文件能否读取,例如,是否有读权限,可以使用is_readable函数;示例代码如下:

<?php
    $file = "test.txt";
    if(is_readable($file) == false) {
        echo "can not read\n";
    }
    else{
        echo "can read \n";
    }
?>

当然也需要判断文件是否存在,可以使用file_exists()函数。示例代码如下:

<?php
    $file = "test.txt";
    if(file_exists($file) == false) {
        echo "file not exist\n";
    }
    else{
    }
    echo "file is exists \n";
?>

读取文件的方法有很多种,此处列举最常用的按行读取方法,示例代码如下:

<?php
    $file = "test.txt";
    $fp = fopen($file,"r");
    while(!feof($fp)){
        echo fgets($fp,1024);
    }    
    fclose($fp);
?>

需要注意的是,读取文件的length参数是可选项,如果忽略,则将继续从流中读取数据直到行结束。指定最大行的长度在利用资源上更为有效。此外,还有fread、file_get_contents等读取文件的方法,此处不再赘述。

15、什么是异常处理与错误处理?
当运行的程序发生异常被抛出时,程序不会继续执行异常处后面的代码,PHP 会尝试查找匹配的“catch”代码块。如果异常没有被捕获,那么将会发生严重的错误,程序会终止或者不受控制地执行。示例代码如下:

<?php
    function GetNum($num)
    {
        if($num > 10)
        {
            throw new Exception("Exception ocur");
        }
        return true;
    }
    GetNum(100);
?>

程序的运行结果为
Uncaught exception 'Exception' with message 'Exception ocur'

从这个例子可以看出,如果不对异常进行处理,那么当程序有异常抛出的时候就会结束执行。而对于对象方法的异常处理,还有另外一种处理方法,下面介绍在PHP中当调用一些不存在的对象方法时的异常处理,从而保证程序正常运行。这主要是通过__call方法来实现的。
方法声明为__call($funname,$arr_value),当被调用方法不存在的时候会默认调用这个方法。
示例代码如下:

class My {
    function __call($n,$v) {
        echo "错误的方法名:".$n;
        echo "错误的参数:".$v;
    }
}

16、什么是内存管理?
内存管理主要是指程序运行时对计算机内存资源的分配、使用和释放等技术,内存管理的目标是高效、快速地分配内存同时及时地释放和回收内存资源。内存管理主要包括是否有足够的内存供程序使用,从内存池中获取可用内存,使用后及时销毁并重新分配给其他程序使用。
在PHP开发过程中,如果遇到大数组等操作,那么可能会造成内存溢出等问题。一些常见的处理方法如下:
1)通过ini_set('memory_limit','64M')方法重置php可以使用的内存大小,一般在远程主机上是不能修改php.ini文件的,只能通过程序设置。注:在safe_mode(安全模式)下,ini_set会失效。
2)另一方面可以对数组进行分批处理,及时销毁无用的变量,尽量减少静态变量的使用,在需要数据重用时,可以考虑使用引用(&)。同时对于数据库、文件操作完要及时关闭,对象使用完要及时调用析构函数等。
3)及时使用unset()函数释放变量,使用时需要注意以下两点:
① unset()函数只能在变量值占用内存空间超过256字节时才会释放内存空间。
② 只有当指向该变量的所有变量都销毁后,才能成功释放内存。

17、与MySQL一样,Redis在使用过程中,也会碰到很多的问题,适当的技巧和优化将大大提高Redis的使用性能,提高服务的质量。现将常见的一些问题总结如下:
1.停止使用keys *操作
keys*操作执行速度将会变慢。因为keys命令的时间复杂度是O(n),其中n是要返回的keys的个数,由此可见这个命令的复杂度就取决于数据量的大小了。当数据量比较大时,在这个操作执行期间,其他任何命令在实例中都无法执行,严重影响了性能。
可以使用scan命令来代替,scan命令通过增量迭代的方式来扫描数据库。
2.定位Redis速度降低的原因
使用INFO commandstats命令来查看所有命令的统计情况,如命令执行了多少次,执行命令所耗费的毫秒数等信息。

18、Memcache的特征和特性
Memcache的特征如下:
1)协议简单。
2)基于libevent的事件处理。
3)内置内存存储方式。
4)Memcached不互相通信的分布式。
Memcache的特性如下:
(1)单个item 最大的数据为1MB。
(2)单进程最大的使用内存为2GB,需要更多内存时可开多个端口。
(3)Memcached是多线程,非阻塞io复用的网络模型,Redis是单线程。
(4)键长最大为250字节。

19、下面可以用于服务器共享session的方式有(    )。
A.利用NFS共享Session数据        B.基于数据库的Session共享
C.基于Cookie的Session共享        D.使用类似BIG-IP的负载设备来实现资源共享
参考答案:A、B、C、D。
分析:共享Session的方式主要有以下几种:
1)基于NFS的Session共享。NFS(Network  File System)最早由Sun公司为解决Unix网络主机间的目录共享而研发。仅需将共享目录服务器mount到其他服务器的本地session目录即可。
2)基于数据库的Session共享。
3)基于Cookie的Session共享。原理是将全站用户的Session信息加密、序列化后以Cookie的方式,统一种植在根域名下(如:.host.com),利用浏览器访问该根域名下的所有二级域名站点时,会传递与之域名对应的所有Cookie内容的特性,从而实现用户的Cookie化Session 在多服务间的共享访问。
4)基于缓存(Memcache)的Session共享。Memcache是一款基于Libevent多路异步I/O技术的内存共享系统,简单的key + value数据存储模式使得代码逻辑小巧高效,因此在并发处理能力上占据了绝对优势,目前能达到2000/s平均查询,并且服务器CPU消耗依然不到10%。
所以,本题的答案为A、B、C、D。

20. How to prevent various security problems?
Common security issues mainly include the following aspects:
1) SQL injection attack. The so-called SQL injection attack means that the attacker inserts SQL commands into the fields of web forms or query strings in page requests to trick the server into executing malicious SQL commands. In some forms, the content entered by the user is directly used to construct dynamic SQL commands or used as input parameters for stored procedures. Such forms are particularly vulnerable to SQL injection attacks. For example, for a website http://www.shuaiqi100.com/New..., id is a query parameter, and a certain piece of information is displayed through the id. In the JSP program, use the SQL statement to read the news: "select * from news where id =” id. If executed normally, you only need to replace id with parameter 2. There is no problem. However, when an illegal user changes the parameter of id to id=2; drop database news, it will be executed. In addition to reading the corresponding news information, the SQL statement will also execute drop database news information, but the latter statement is illegal.
Because SQL injection attacks use legal SQL statements, this attack cannot be checked by firewalls, and because it is applicable to any database based on the SQL language standard, it is particularly harmful. Despite this, there are currently many methods to prevent SQL injection attacks. Specifically, there are the following methods: Use prepared statements and parameters to be sent to the database server for parsing. The parameters will be treated as ordinary characters. After using this method, the attacker cannot inject malicious SQL. So how to prevent SQL injection attacks? Here are some commonly used methods:
① The prepared statements and parameters are sent to the database server for parsing respectively.
② Use the function addslashes() to escape the submitted content.
③ Turning on magic_quotes_gpc=on; in the PHP configuration file will automatically convert the SQL statement queried by the user, which plays a significant role in preventing SQL injection.
④ In the PHP configuration file, set register_globals to off to turn off global variable registration.
⑤ In the PHP configuration file, turn on the safe mode safe_mode=on;.
⑥ Try not to omit small quotation marks and single quotation marks when writing SQL statements.
⑦ Improve the naming skills of database tables and fields. Name some important fields according to the characteristics of the program and give them names that are not easy to guess.
⑧ Control error messages, turn off the output of error messages, write error messages to log files, and do not expose error messages on the website.
2) Database operation security issues. For example, user permissions are not restricted, and misoperations such as update, delete, and insert cause system security problems.
The solution is to grant different permissions to different users, so as to ensure that only users with permissions can perform specific operations.
3) There is no verification of user http request method. Malicious users can simulate http requests to websites to cause malicious attacks. In order to prevent such attacks, it is necessary to check whether the access source in the user's http request is trustworthy, filter the referer in the http header, and only allow access to sites in this domain.
4) There is no verification of the uniqueness of the form source, and it cannot identify whether it is a legal form submission or a form submission forged by a hacker.
To prevent hackers from forging form submissions, you can use a one-time token Token. The server generates a random string using a certain strategy and saves it in the Session as a token. Then when the requested page is sent, the token is sent together with other information in the form of a hidden domain, and is sent on the receiving page. The token in the received information is compared with the token in the Session. Only if they are consistent, the request will be processed. Otherwise, the request will be rejected. This ensures that the source of the form is unique and prevents hackers from forging form submissions.

21、PHP的开发框架有哪些?
CodeIgniter是一个轻量级的PHP开发框架,具有快速开发、灵活性高等优点,它特别适合互联网公司的快速迭代场景,因此很受欢迎,据说腾讯、去哪儿网等应用场景都使用了这个框架。CodeIgniter具有动态实例化、松耦合、组件单一性等很多优点。动态实例化是指组件的导入和函数在执行时才会生效。松耦合是指系统模块之间的关联依赖很少,确保系统具有很好的重用性和灵活性。框架内的类和功能都是高度自治的,具有非常好的组件单一性。
在CodeIgniter中,模型代表数据结构,包含取出、插入、更新数据库的这些功能。视图通常是一个网页,但是在CodeIgniter中,一个视图也可以是一个页面片段,如头部、顶部HTML代码片段。它还可以是一个RSS页面,或其他任一页面。控制器相当于一个指挥者,或者说是一个“中介”,它负责联系视图和模型,以及其他任何处理HTTP请求和产生网页的资源。
Zend Framework是完全基于PHP语言的针对Web应用开发的框架,与众多的其他PHP开发框架相比,Zend Framework是一个PHP“官方”的框架,它由Zend公司负责开发和维护。Zend Framework同样基于MVC模式,Zend Framework采用了ORM(Object Relational Mapping,对象关系映射)思路,这是一种为了解决面向对象编程与关系数据库存在的互不匹配现象的技术。简单地说,这种技术将数据库中的一个表映射为程序中的一个对象,表中的字段映射为对象的属性,然后通过提供的方法完成对数据库的操作。就这一点而言,Zend Framework很相似于现在流行的非PHP的开发框架Ruby on Rails。
ThinkPHP是一个快速、兼容而且简单的轻量级国产PHP开发框架,诞生于2006年初,原名FCS,2007年元旦正式更名为ThinkPHP,其遵循Apache2开源协议发布,从Struts结构移植过来并做了改进和完善,同时也借鉴了国外很多优秀的框架和模式,使用面向对象的开发结构和MVC模式,融合了Struts的思想和TagLib(标签库)、RoR的ORM映射和ActiveRecord模式。
此外,还有FleaPHP、CakePHP等很多优秀的框架,此处就不一一列举,它们本质上都是基于MVC的架构,下面着重介绍一下在互联网公司使用比较广泛的CI框架。

3、PHP+mysql

1、问题:设教务管理系统中有三个基本表:
学生信息表S(SNO, SNAME, AGE, SEX),其属性分别表示学号、学生姓名、年龄和性别。
选课信息表SC(SNO, CNO, SCGRADE),其属性分别表示学号、课程号和成绩。
课程信息表C(CNO, CNAME, CTEACHER),其属性分别表示课程号、课程名称和任课老师姓名。
1)把SC表中每门课程的平均成绩插入另外一个已经存在的表SC_C(CNO, CNAME, AVG_GRADE)中,其中AVG_GRADE表示的是每门课程的平均成绩。
INSERT INTO SC_C(CNO, CNAME, AVG_GRADE)
SELECT SC.CNO, C.CNAME, AVG(SCGRADE) FROM SC, C WHERE SC.CNO = C.CNO GROUP BY SC.CNO

2)规定女同学选修何昊老师的课程成绩都应该在80分以上(包含80分)。
ALERT TABLE SC, S, C
ADD CONSTRAINT GRADE CHECK(SCGRADE>=80)
WHERE SC.CNO=C.CNO  AND  SC.SNO=S.SNO AND C.CTEACHER='何昊' AND  S.SEX=

"女"

3)从SC表中把何昊老师的女学生选课记录删除。
DELETE FROM SC WHERE CNO=(SELECT CNO FROM C WHERE C.CTEACHER ='何昊') AND SNO IN (SELECT SNO FROM S WHERE SEX='女')

4)找出没有选修过“何昊”老师讲授课程的所有学生姓名。
SELECT SNAME FROM S
WHERE NOT EXISTS(
SELECT * FROM SC,C WHERE SC.CNO=C.CNO AND CNAME='何昊' AND SC.SNO=S.SNO)

5)列出有两门以上(含两门)不及格课程(成绩小于60)的学生姓名及其平均成绩。
SELECT S.SNO,S.SNAME,AVG_SCGRADE=AVG(SC.SCGRADE)

    FROM S,SC,(
    SELECT SNO FROM SC WHERE SCGRADE<60 GROUP BY SNO
    HAVING COUNT(DISTINCT CNO)>=2)A WHERE S.SNO=A.SNO AND SC.SNO = A.SNO
    GROUP BY S.SNO,S.SNAME

6)列出既学过“1”号课程,又学过“2”号课程的所有学生姓名。
SELECT S.SNO,S.SNAME
FROM S,(SELECT SC.SNO FROM SC,C
WHERE SC.CNO=C.CNO AND C.CNAME IN('1','2')

GROUP BY SNO
HAVING COUNT(DISTINCT CNO)=2

)SC WHERE S.SNO=SC.SNO

7)列出“1”号课成绩比“2”号同学该门课成绩高的所有学生的学号。
SELECT S.SNO,S.SNAME
FROM S,(
SELECT SC1.SNO
FROM SC SC1,C C1,SC SC2,C C2
WHERE SC1.CNO=C1.CNO AND C1.NAME='1'
AND SC2.CNO=C2.CNO AND C2.NAME='2'
AND SC1.SCGRADE>SC2.SCGRADE
)SC WHERE S.SNO=SC.SNO

8)列出“1”号课成绩比“2”号课成绩高的所有学生的学号及其“1”号课和“2”号课的成绩。
SELECT S.SNO,S.SNAME,SC.[1号课成绩],SC.[2号课成绩]

FROM S,(
SELECT SC1.SNO,[1号课成绩]=SC1.SCGRADE,[2号课成绩]=SC2.SCGRADE

FROM SC SC1,C C1,SC SC2,C C2
WHERE SC1.CNO=C1.CNO AND C1.NAME='1'
AND SC2.CNO=C2.CNO AND C2.NAME='2'

AND SC1.SCGRADE>SC2.SCGRADE
)SC WHERE S.SNO=SC.SNO

2、UNION和UNION ALL有什么区别?
UNION在进行表求并集后会去掉重复的元素,所以会对所产生的结果集进行排序运算,删除重复的记录再返回结果。
而UNION ALL只是简单地将两个结果合并后就返回。因此,如果返回的两个结果集中有重复的数据,那么返回的结果集就会包含重复的数据。
从上面的对比可以看出,在执行查询操作的时候,UNION ALL要比UNION快很多,所以,如果可以确认合并的两个结果集中不包含重复的数据,那么最好使用UNION ALL。例如,如下有两个学生表Table1和Table2。
Table1
C1    C2
1    1
2    2
3    3

Table2
C1    C2
3    3
4    4
1    1
select from Table1 union select from Table2 的查询结果为
C1    C2
1    1
2    2
3    3
4    4
select from Table1 union all select from Table2 的查询结果为
C1    C2
1    1
2    2
3    3
3    3
4    4
1    1

3、什么是数据库三级封锁协议?
众所周知,基本的封锁类型有两种:排它锁(X锁)和共享锁(S锁)。所谓X锁是事务T对数据A加上X锁时,只允许事务T读取和修改数据A。所谓S锁是事务T对数据A加上S锁时,其他事务只能再对数据A加S锁,而不能加X锁,直到T释放A上的S锁。若事务T对数据对象A加了S锁,则T就可以对A进行读取,但不能进行更新(S锁因此又称为读锁),在T释放A上的S锁以前,其他事务可以再对A加S锁,但不能加X锁,从而可以读取A,但不能更新A。
在运用X锁和S锁对数据对象加锁时,还需要约定一些规则,例如,何时申请X锁或S锁、持锁时间、何时释放等,称这些规则为封锁协议(Locking Protocol)。对封锁方式规定不同的规则,就形成了各种不同的封锁协议。一般使用三级封锁协议,也称为三级加锁协议。该协议是为了保证正确的调度事务的并发操作。三级加锁协议是事务在对数据库对象加锁、解锁时必须遵守的一种规则。下面分别介绍这三级封锁协议。
一级封锁协议:事务T在修改数据R之前必须先对其加X锁,直到事务结束才释放。事务结束包括正常结束(COMMIT)和非正常结束(ROLLBACK)。一级封锁协议可以防止丢失修改,并保证事务T是可恢复的。使用一级封锁协议可以解决丢失修改问题。在一级封锁协议中,如果仅仅是读数据不对其进行修改,是不需要加锁的,它不能保证可重复读和不读“脏”数据。
二级封锁协议:一级封锁协议加上事务T在读取数据R之前必须先对其加S锁,读完后方可释放S锁。二级封锁协议除防止了丢失修改,还可以进一步防止读“脏”数据。但在二级封锁协议中,由于读完数据后即可释放S锁,所以它不能保证可重复读。
三级封锁协议:一级封锁协议加上事务T在读取数据R之前必须先对其加S锁,直到事务结束才释放。三级封锁协议除防止了丢失修改和不读“脏”数据外,还进一步防止了不可重复读。

4、以下关于mysql_pconnect的说法中,正确的是(    )。
A.与数据库进行多连接                    B.与mysql_connect功能相同
C.与@mysql_connect功能相同                D.与数据库建立持久连接
参考答案:D。
分析:mysql_pconnect()函数打开一个到 MySQL 服务器的持久连接。
mysql_pconnect()和mysql_connect()非常相似,虽然只多了一个p,但它们有两个主要区别:当连接的时候本函数将先尝试寻找一个在同一个主机上用同样的用户名和密码已经打开的(持久)连接,如果找到,则返回此连接标识而不打开新连接。其次,当脚本执行完毕后到SQL服务器的连接不会被关闭,此连接将保持打开以备以后使用(mysql_close()不会关闭由mysql_pconnect()建立的连接)。所以,选项D正确。

[Real Question 204] PDO interacts with the database by executing SQL queries. It can be divided into many different strategies. Which method to use depends on what operation you want to do. If you send a DML statement to the database, the most appropriate way is ( ).
A. Use the exec() method in the PDO object
B. Use the query() method in the PDO object
C. Use the prepare() method in the PDO object and the execute() method in the PDOStatement object to combine
D. All of the above methods are possible
Reference answer: A.
Analysis: The PDO->exec() method is mainly for operations that do not return a result set, such as INSERT, UPDATE, DELETE and other operations. The result it returns is the number of columns affected by the current operation. Therefore, option A is correct.

5. The commonly used function for traversing data in PHP’s mysql series of functions is ( ).
A. mysql_fetch_row, mysql_fetch_assoc, mysql_affetced_rows
B. mysql_fecth_row, mysql_fecth_assoc, mysql_affetced_rows
C. mysql_fetch_rows, mysql_fetch_array, mysql_fetch_assoc
D. mysql_fecth_row, mysql_fecth_array, mysql_fecth_assoc
Reference answer: D.
Analysis: The most commonly used mysql series functions. The commonly used traversal data functions include mysql_fetch_row, mysql_fetch_array and mysql_fetch_assoc, but mysql_fetch_rows does not exist.
So, the answer to this question is D.

6. The standard syntax for changing table field names is ( ).
A. alter table table name add field word type [first|after]
B. alter table table name drop field [first|after]
C. alter table table name change original name new name new type [first|after]
D. alter table table name modify original name field type [first|after]
Reference answer: C.
Analysis: The syntax for modifying table field names: alter table table name change original field name new field name type;.
Syntax for modifying field types: alter table table name modify field name type;.
Add a field: alter table table name add column field name type not null (or default null); adding a new field is not empty by default (default is empty).
Delete a field: alter table table name drop column new field name;.


The above is the detailed content of The latest summary of 2018PHP interview questions (with answers). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete
Previous article:What is SessionNext article:What is Session