Two sets of PHP interview questions (useful for interviews)_PHP tutorial
WBOYOriginal
2016-07-14 10:09:35913browse
1. What is the difference between the get and post submission methods in the form?
Answer: get is to send a request through the HTTP protocol and receive it through url parameters, while post is entity data and can submit a large amount of information through a form.
2. What is the difference between session and cookie?
Answer: session: stores the global unique variable accessed by the user, stored in the (session_dir) location in the directory specified by PHP on the server
Cookie: Used to store consecutive visits to a page. It is stored on the client. For cookies, it is stored in the Temp directory of the user's WIN.
Both can set the length of time through time
3. What are transactions in the database?
Answer: A transaction is an ordered set of database operations as a unit. A transaction is considered successful if all operations in the group succeed, even if only one operation fails, the transaction is not successful. If all operations are completed,
The transaction is committed, and its modifications will affect all other database processes. If an operation fails, the transaction is rolled back and the effects of all operations in the transaction are canceled.
Brief question:
1. Use PHP to print out the time of the previous day in the format of 2006-5-10 22:21:21 (2 points)
2. The difference between echo(), print() and print_r() (3 points)
Answer: echo is a PHP statement, print and print_r are functions, statements have no return value, and functions can have return values (even if they are useless)
print() can only print out the value of simple type variables (such as int, string)
print_r() can print out the value of complex type variables (such as arrays, objects)
echo Output one or more strings
3. A template that allows HTML and PHP to be used separately (1 point)
5. What tools are used for version control? (1 point)
Answer: cvs, svn, vss;
6. How to implement string flipping? (3 points)
Answer: echo strrev($a);
7. Methods to optimize MYSQL database. (4 points, write more and get more)
Answer:
1. Select the most applicable field attribute, reduce the length of the defined field as much as possible, and try to set the field to NOT NULL, such as 'province, gender', it is best to set it to ENUM
2. Use connection (JOIN) instead of subquery:
a. Delete customers without any orders: DELETE FROM customerinfo WHERE customerid NOT in (SELECT customerid FROM orderinfo)
b. Extract all customers without orders: SELECT FROM customerinfo WHERE customerid NOT in (SELECT customerid FROM orderinfo)
c. Improve b’s speed optimization: SELECT FROM customerinfo LEFT JOIN orderid customerinfo.customerid=orderinfo.customerid
WHERE orderinfo.customerid IS NULL
3. Use UNION to replace manually created temporary tables
a. Create a temporary table: SELECT name FROM `nametest` UNION SELECT username FROM `nametest2`
4. Transaction processing:
a. Ensure data integrity, such as adding and modifying at the same time. If both are true, both will be executed. If one fails, it will fail.
mysql_query("BEGIN");
mysql_query("INSERT INTO customerinfo (name) VALUES ('$name1')";
mysql_query("SELECT * FROM `orderinfo` where customerid=".$id");
mysql_query("COMMIT");
5. Lock the table and optimize transaction processing:
a. We use a SELECT statement to retrieve the initial data, and through some calculations, use an UPDATE statement to update the new values into the table.
A LOCK TABLE statement containing the WRITE keyword ensures that
There will be no other access to insert, update or delete inventory
mysql_query("SELECT customerid FROM `customerinfo` where id=".$id);
mysql_query("UPDATE `orderinfo` SET ordertitle='$title' where customerid=".$id);
mysql_query("UNLOCK TABLES");
6. Use foreign keys to optimize lock tables
a. Map the customerid in customerinfo to the customerid in orderinfo,
Any record without a legal customerid will not be written to orderinfo
CREATE TABLE customerinfo
(
customerid INT NOT NULL,
PRIMARY KEY(customerid)
)TYPE = INNODB;
CREATE TABLE orderinfo
(
orderid INT NOT NULL,
customerid INT NOT NULL,
PRIMARY KEY(customerid,orderid),
FOREIGN KEY (customerid) REFERENCES customerinfo
(customerid) ON DELETE CASCADE
)TYPE = INNODB;
Note: 'ON DELETE CASCADE', this parameter ensures that when a record in the customerinfo table is deleted, the order will also be deleted
All records of the user in the table. Note that when using foreign keys, the transaction security type must be defined as INNODB;
7. Create index:
a. Format:
(Normal index)->
Create: CREATE INDEX ON tablename (index field)
Modification: ALTER TABLE tablename ADD INDEX [index name] (index field)
Create a table with a specified index: CREATE TABLE tablename([...],INDEX[index name](index field))
(unique index)->
Create: CREATE UNIQUE ON tablename (index field)
Modification: ALTER TABLE tablename ADD UNIQUE [index name] (index field)
Create a table with a specified index: CREATE TABLE tablename([...],UNIQUE[index name](index field))
(primary key)->
It is a unique index, which is usually created when creating a table. The format is:
CREATA TABLE tablename ([...],PRIMARY KEY[index field])
8. Optimize query statements
a. It is best to perform comparison operations on the same fields and minimize function operations on the established index fields
Example 1:
SELECT * FROM order WHERE YEAR(orderDate)<2008;(Slow)
SELECT * FROM order WHERE orderDate<"2008-01-01";(Quick)
Example 2:
SELECT * FROM order WHERE addtime/7<24;(Slow)
SELECT * FROM order WHERE addtime<24*7;(fast)
Example 3:
SELECT * FROM order WHERE title like "%good%";
SELECT * FROM order WHERE title>="good" and name<"good";
8. What does PHP mean (get 1 point)
Answer: PHP is a server-based scripting language for creating dynamic websites. You can use PHP and HTML to generate the website homepage
9. What is the function of MYSQL to obtain the current time?, and the function of formatting date is (2 points)
Answer: now(), date()
10. A method to intercept Chinese text strings without garbled characters. (3 points)
Answer: function GBsubstr($string, $start, $length) {
if(strlen($string)>$length){
$str=null;
$len=$start+$length;
for($i=$start;$i<$len;$i++){
if(ord(substr($string,$i,1))>0xa0){
$str.=substr($string,$i,2);
$i++;
}else{
$str.=substr($string,$i,1);
}
}
return $str.'...';
}else{
return $string;
}
}
11. Have you ever used version control software? If so, what is the name of the version control software you used? (1 point)
12. Have you ever used a template engine? If so, what is the name of the template engine you used? (1 point)
Answer: Used, smarty
13. Please briefly describe your most proud development work (4 points)
Answer: Information classification
14. For websites with large traffic, what methods do you use to solve the traffic problem? (4 points)
Answer: Confirm whether the server hardware is sufficient to support the current traffic, separate database reading and writing, and optimize the data table,
Program function rules prohibit external hot links, control the download of large files, and use different hosts to divert main traffic
15. Use PHP to write the code to display the client IP and server IP 1 point)
Print server IP:echo gethostbyname("www.bolaiwu.com")
16. What is the difference between the include and require statements? To avoid including the same file multiple times, you can replace them with (?) statements? (2 points)
Answer: require->require is an unconditional inclusion, that is, if require is added to a process, require will be executed first regardless of whether the condition is true or not
include->include has a return value, but require does not (maybe because require is faster than include)
Note: require is fatal when the included file does not exist or has a syntax error, and include is not
17. How to modify the survival time of SESSION (1 minute).
Answer: Method 1: Set session.gc_maxlifetime in php.ini to 9999 and restart apache
Method 2:$savePath = "./session_save_dir/";
$lifeTime = hours * seconds;
session_save_path($savePath);
session_set_cookie_params($lifeTime);
session_start();
Method 3: setcookie() and session_set_cookie_params($lifeTime);
18. There is a web page address, such as the homepage of the PHP Development Resource Network: http://www.phpres.com/index.html, how to get its content? ($1 point)
19. In HTTP 1.0, the meaning of status code 401 is (?); if the prompt "File not found" is returned, the header function can be used, and its statement is (?); (2 points)
Answer: Status 401 means not authorized, header("Location:www.xxx.php");
12. In PHP, heredoc is a special string, and its end mark must be? (1 point)
Answer: The syntax of heredoc is to use "<<<" plus self-defined paired tags, and the text within the tag range is regarded as a string
Example:
$str = <<
my name is Jiang Qihui!
SHOW;
13. Talk about the advantages and disadvantages of asp, php and jsp (1 point)
Answer: ASP’s full name is Active Server Pages, which is a WEB server-side development environment that can be used to generate and operate
Run dynamic, interactive, high-performance WEB service applications. ASP uses the scripting language VB Script (Java script
) as its own development language.
PHP is a cross-platform server-side embedded scripting language. It borrows a lot of syntax from C, Java and Perl languages
, and coupled with PHP's own features, allowing WEB developers to quickly write dynamically generated pages. It supports most of the current
Database. Another point is that PHP is completely free. You don’t need to spend money. You can download it from the PHP official site (http://www.php.ne
t) Free download. And you have unrestricted access to the source code, and you can even add the features you need.
JSP is a new generation website development language launched by Sun. It completely solves a common problem of ASP and PHP currently -
Script-level execution (it is said that PHP4 has also been compiled and run with the support of Zend). Sun uses its own expertise in Jav
The extraordinary achievements in a have made Java a new fruit in addition to Java applications and Java Applets, which is Js
p——Java Server Page. Jsp can complete a powerful website with the support of Serverlet and JavaBean
Program.
All three provide the ability to mix certain program code in HTML code and have the language engine interpret and execute the program code.
But the JSP code is compiled into Servlet and interpreted and executed by the Java virtual machine. This compilation operation is only performed on the JSP page
Occurs on first request. In ASP, PHP, and JSP environments, HTML code is mainly responsible for describing the display style of information
, and program code is used to describe the processing logic. Ordinary HTML pages only rely on the web server, while ASP and PH
P. JSP pages require additional language engines to analyze and execute program code. The execution results of the program code are re-embedded into
HTML code, and then sent to the browser together. ASP, PHP, and JSP are all web server-oriented technologies
, the client browser does not require any additional software support.
14. Talk about your understanding of mvc (1 point)
Answer: An application completed by model, view, and controller
The model sends the functions to be implemented to the controller, and the controller receives the organized functions and passes them to the view;
15. Write the SQL of the names of the ten people with the most posts, using the following table: members (id, username, posts, pass, email) (2 points)
Answer: SELECT * FROM `members` ORDER BY posts DESC limit 0,10;
16. Please explain the difference between passing by value and passing by reference in PHP. When to pass by value and when to pass by reference? (2 points)
Answer: Pass by value: Any changes to the value within the function scope will be ignored outside the function
Pass by reference: Any changes to the value within the scope of the function will also reflect these modifications outside the function
Advantages and Disadvantages: When passing by value, PHP must copy the value. Especially for large strings and objects, this can be a costly operation.
Passing by reference does not require copying the value, which is very good for improving performance.
17. What is the function of error_reporting in PHP? (1 point)
Answer: Set error level and error message reporting
18. Please write a function to verify whether the format of the email is correct (2 points)
31. Which of the following options does not add john to the users array? (1 point)
(a) $users[] = ‘john’;
(b) array_add($users,’john’);
(c) array_push($users,‘john’);
(d) $users ||= ‘john’; [ a , c ]
32. Will the following program be input? (1 point)
$num = 10;
Function multiply(){
$num = $num * 10;
}
multiply();
echo $num;
?>
Output: 10
33. Use PHP to write a simple query to find out all the content named "Zhang San" and print it out (2 points)
Table name User
Name Tel Content Date
Zhang San 13333663366 Graduated from college 2006-10-11
Zhang San 13612312331 Bachelor’s degree 2006-10-15
Zhang Si 021-55665566 Graduated from technical secondary school 2006-10-15
Please complete the code according to the above question:
$mysql_db=mysql_connect("local","root","pass");
@mysql_select_db("DB",$mysql_db);
$result = mysql_query("SELECT * FROM `user` WHERE name='Zhang San'");
while($rs = mysql_fetch_array($result)){
echo $rs["tel"].$rs["content"].$rs["date"];
}
34. How to use the following classes and explain what they mean? (3)
class test{
function Get_test($num){
$num=md5(md5($num)."En");
Return $num;
}
}
Answer:$testnum = "123";
$object = new test();
$encrypt = $object->Get_test($testnum);
echo $encrypt;
The class test contains the Get_test method, and the instantiated class calls the method multi-string encryption
35. Write the format of SQL statements: insert, update, delete (4 points)
Table name User
Name Tel Content Date
Zhang San 13333663366 Graduated from college 2006-10-11
Zhang San 13612312331 Bachelor’s degree 2006-10-15
Zhang Si 021-55665566 Graduated from technical secondary school 2006-10-15
(a) There is a new record (Xiao Wang 13254748547 graduated from high school 2007-05-06). Please use SQL statements to add it to the table
mysql_query("INSERT INTO `user` (name,tel,content,date) VALUES
('Xiao Wang','13254748547','High School Graduation','2007-05-06')")
(b) Please use sql statement to update Zhang San’s time to the current system time
$nowDate = date("Ymd");
mysql_query("UPDATE `user` SET date='".$nowDate."' WHERE name='Zhang Shan'");
(c) Please write to delete all records named Zhang Si
mysql_query("DELETE FROM `user` WHERE name='Zhang Si'");
36. Please write the meaning of data type (int char varchar datetime text); what is the difference between varchar and char (2 points)
Answer: int is a numeric type, char fixed length string, varchar actual length string, datetime date and time type, text text string
The field of char is fixed to the length set by the created table, and varchar is a variable-length character
38. Write the output result of the following program (1 point)
$b=201;
$c=40;
$a=$b>$c?4:5;
echo $a;
?>
Answer: 4
39. Is there a function that detects whether a variable is set? What is the function that detects whether it is empty? (2 points)
Answer:isset($str),empty($str);
40. What is the function to obtain the total number of query result sets? (1 point)
Answer: mysql_num_rows($result);
41. $arr = array('james', 'tom', 'symfony'); Please print out the value of the first element (1 point)
Answer: echo $array[0];
42. Please separate the array values in question 41 with ',' signs and merge them into string output (1 point)
Answer: for($i=0;$i
43. $a = 'abcdef'; Please take out the value of $a and print out the first letter (1 point)
Answer: echo $a{0} or echo substr($a,0,1)
44. Can PHP be connected to databases such as sql server/oracle? (1 point)
Answer: Of course
45. Please write the PHP5 permission control modifier (3 points)
Answer: public (public), private (private), protected (inherited)
46. Please write the constructor and destructor of php5 (2 points)
Answer: __construct , __destruct
47. Complete the following:
(1) Create a news release system with the table name message and the following fields (3 points)
id article id
Title Article title
content article content
category_id article category id
hits Click count
Answer:CREATE TABLE 'message'(
'id' int(10) NOT NULL auto_increment,
'title' varchar(200) default NULL,
'content' text,
'category_id' int(10) NOT NULL,
'hits' int(20),
PRIMARY KEY('id');
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
(2) The same news release system as above: the comment table records the content of user replies, and the fields are as follows (4 points)
Comment_id reply id
id article id, associated with the id in the message table
comment_content reply content
Now you need to query the database to get a list of article titles in the following format, and sort them by the number of replies, with the highest reply at the top
Article id Article title Number of clicks Number of replies
Use a SQL statement to complete the above query. If the article has no replies, the number of replies will be displayed as 0
Answer: SELECT message.id id,message.title title,IF(message.`hits` IS NULL,0,message.`hits`) hits,
IF(comment.`id` is NULL,0,count(*)) number FROM message LEFT JOIN
comment ON message.id=comment.id GROUP BY message.`id`;
(3) In the above content management system, the category table stores classification information, and the fields are as follows (3 points)
category_id int(4) not null auto_increment;
categroy_name varchar(40) not null;
When the user enters an article, select the article category by selecting the drop-down menu
Write how to implement this drop-down menu
Answer: function categoryList()
{
$result=mysql_query("select category_id,categroy_name from category")
or die("Invalid query: " . mysql_error());
print("
while($rowArray=mysql_fetch_array($result))
{
print("/n");
}
print("");
}
Programming questions:
1. Write a function to retrieve the file extension from a standard URL as efficiently as possible
For example: http://www.sina.com.cn/abc/de/fg.php?id=1 You need to remove php or .php
Answer 1:
function getExt($url){
$arr = parse_url($url);
$file = basename($arr['path']);
$ext = explode(".",$file);
return $ext[1];
}
Answer 2:
function getExt($url) {
$url = basename($url);
$pos1 = strpos($url,".");
$pos2 = strpos($url,"?");
if(strstr($url,"?")){
return substr($url,$pos1 + 1,$pos2 - $pos1 - 1);
} else {
return substr($url,$pos1);
}
}
2. In HTML language, the meta tag in the header of the page can be used to output the encoding format of the file. The following is a standard meta statement
Please use PHP language to write a function to change the charset part value in a similar meta tag in a standard HTML page to big5
Please note:
1. Need to process the complete html page, that is, not just this meta statement
2. Ignore case
3. ' and " are interchangeable here
4. The quotation marks on both sides of 'Content-Type' can be ignored, but the quotation marks on both sides of 'text/html; charset=gbk' are not allowed
5. Pay attention to excess spaces
3. Write a function to calculate the relative paths of two files
For example $a = '/a/b/c/d/e.php';
$b = '/a/b/12/34/c.php';
Calculate that the relative path of $b relative to $a should be ../../c/d and add () to
1. In PHP, the name of the current script (excluding path and query string) is recorded in the predefined variable __$_SERVER['PHP_SELF']__; and the URL linking to the current page is recorded in the predefined variable __$_SERVER['PHP_SELF']__ Define variable __$_SERVER['HTTP_REFERER']__
中
2. Execute the program segment will output __0__.
3. In HTTP 1.0, the meaning of status code 401 is ____; if a "File not found" prompt is returned, the header function can be used, and its statement is ____.
4. The function of the array function arsort is to __reverse sort the array and maintain the index relationship__; the function of the statement error_reporting(2047) is to __report all errors and warnings__.
5.The database connection string format in PEAR is____.
6. Write a regular expression to filter all JS/VBS scripts on the web page (that is, remove the scrīpt tag and its content): preg_replace("//si", "newinfo", $script);
7. Install PHP as an Apache module. In the file http.conf, first use the statement ____ to dynamically load the PHP module, and then use the statement ____ to make Apache treat all files with the extension php as PHP script processing.
8. The statements include and require can include another file into the current file. The difference between them is ____; in order to avoid including the same file multiple times, you can replace them with the statement __require_once||include_once__.
9. The attributes of a class can be serialized and saved to the session, so that the entire class can be restored later. The function used for this is ____.
10. The parameter of a function cannot be a reference to a variable, unless __allow_call_time_pass_reference boolean__ is set to on in php.ini.
11. The meaning of LEFT JOIN in SQL is __natural left outer link__. If tbl_user records the student's name and student ID, tbl_score records the student's student ID (some students were expelled after the exam and there is no record of them)
And test scores (score) and test subjects (subject), if you want to print out the names of each student and the corresponding total score of each subject, you can use the SQL statement ____.
12. In PHP, heredoc is a special string, and its end mark must be____.
Programming questions:
13. Write a function that can traverse all files and subfolders in a folder.
Answer:
function my_scandir($dir)
{
$files = array();
if ( $handle = opendir($dir) ) {
while ( ($file = readdir($handle)) !== false ) {
if ( $file != ".." && $file != "." ) {
if ( is_dir($dir . "/" . $file) ) {
$files[$file] = scandir($dir . "/" . $file);
}else {
$files[] = $file;
}
}
} }
closedir($handle);
return $files;
}
}
14. Briefly describe the implementation principle of infinite classification in the forum.
Answer:
/*
The data table structure is as follows:
CREATE TABLE `category` (
`categoryID` smallint(5) unsigned NOT NULL auto_increment,
`categoryParentID` smallint(5) unsigned NOT NULL default '0',
`categoryName` varchar(50) NOT NULL default '',
PRIMARY KEY (`categoryID`)
) ENGINE=MyISAM DEFAULT CHARSET=gbk;
INSERT INTO `category` ( `categoryParentID`, `categoryName`) VALUES
(0, 'First level category'),
(1, 'Second level category'),
(1, 'Second level category'),
(1, 'Second level category'),
(2, 'Third level category'),
(2, '333332'),
(2, '234234'),
(3, 'aqqqqqd'),
(4, 'Haha'),
(5, '66333666');
*/
//Specify the category id variable $category_id, and then return all subcategories of the category
//$default_category is the default selected category
function Get_Category($category_id = 0,$level = 0, $default_category = 0)
{
global $DB;
$sql = "SELECT * FROM category ORDER BY categoryID DESC";