


Collection of Frequently Asked Questions for PHP Beginners Revised Edition (21 Questions and Answers)_PHP Tutorial
1. How to connect two strings?
Answer: To connect two strings in PHP, you can directly use the "." operator symbol, such as $newStr="Zhang"."san". In Java, you use the "+" operator symbol, so don't be confused.
2. How to calculate the length of a string?
Answer: $str="test";$length=strlen($str); that is, use the strlen(str) function.
3. How to split a string according to a certain delimiter?
Answer: Use the explode(delim,str) function, for example $arr=explode("::","a::bdf::dfsdf"); This function returns an array. In java, you can use the split function of String object.
4. How to get the parameter value in the http request?
Answer: If it is a GET request, use $_GET[paramName]. If it is a POST request, use $_POST[paramName], for example: $email=$_POST["usermail"].
5. Can classes be used in PHP like Java?
A: Yes, but the mechanism and specific usage may be different.
6. Can you give an example of using a for loop?
Answer:
for($i=0;$iecho $i;
}
7. How to get variables in php in javascript?
Answer: An example is as follows:
$username= $_POST["username"];
?>
<script> <BR>var username="<?php echo $username ?>"; <BR></script>
8. How to delete a file?
Answer: Use the unlink(filename) function. Of course, the program must have permission to delete the file. The PHP virtual space we use may have restrictions on some files, so permission errors may occur.
9. I defined a class User and declared a method getName() of the class. Why does it report an error when I use $user=new User;$name=$user.getName()?
Answer: Pay attention to the way class members are referenced in PHP. The above reference should be $name=$user->getName(), that is, use the -> symbol instead of the "." used in
Java. "Number.
10. I applied for a php virtual space without mysql support. How can I access application data?
Answer: It is not necessary to use a database to access data. It is also good to use a file system. In addition, even if a database is used, it is not necessary to use a database like mysql
, oracle, etc. You can also use some text Database, such as txtsql, so you don’t have to rent the relatively expensive mysql
database space.
11. I applied for a PHP space without a database. My current application data is stored in files, but there is a security issue, that is
Visitors can view the contents of these files through the URL. , how do I protect the contents of these files?
Answer: There are three recommended methods:
1) If the PHP space you rent allows setting the http access permissions of the directory, then just set it.
2) The file content can be encrypted, so even if it is downloaded, it will not be of much value.
3) You can change the suffix of these files to .php, that is, use PHP files to store application information. In this case, visitors will not be able to access
the real content of these files through http. Of course, the content in these files The content must be in correct PHP syntax, and the content must use the hidden syntax
in PHP syntax to hide the information. For example, a file that stores account information is as follows:
users.php
:::user1:password1::user2:password2::user3: password3:::
*/
?>
Use PHP's iconv function, the signature is:
$str=iconv(fromEncode,toEncode,str);
For example:
$str="php string transcoding";
$ str=iconv("utf-8","gbk",$str);//Convert a string from utf-8 format to gbk format
Transcoding is a very important issue, for example, many blogs currently provide RSS is returned in UTF-8, so it needs to be converted to display correctly.
13. How to read the HTML content of a web page?
The concept of files in PHP is similar to the concept of file streams in Java. Many file reading functions accept input streams not only from the local file system, but also from network files. One of them is introduced below. Method:
$handle = fopen ($ url, "rb");
$contents = "";
$count=0;
do {
$data = fread($handle, 1000000);
$count++;
if (strlen($data) == 0) {
break;
}
$contents .= $data;
} while(true);
fclose ($handle) ;
return $contents;
}
14. How to operate mysql database in PHP?
In order to make it easier for beginners to get started with mysql operations, I introduce some commonly used operations:
1) Database connection and closure
$dbhost = "";
$dbuser = "";
$dbpw = "";
$dbname = "";
$link = mysql_connect($dbhost, $dbuser, $dbpw) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname);
...//This is specific to the database Operation, the following examples will no longer write the database connection and closing operations
mysql_close($link);
2) Insert new data into the table
mysql_query("insert into mytable( id,name) values('".$id."','".$name."')");
The above is to insert a piece of data into the id and name fields of the mytable table.
3) Query data from the table
$rs=mysql_query("select * from mytable mt where mt.id='001'");
4) Delete data from the table
$rs =mysql_query("delete from mytable mt where mt.id='001'");
5) For complex queries, such as select clauses, versions below mysql3.22 do not support it, so many times when PHP writes complex SQL If you can't get the result, this is actually not PHP's fault, but the reason for the lower version of MySQL.
6) For the result set returned by select, you can do the following:
For returning a result, you can do the following:
$row=mysql_fetch_object($rs);
$id=$row->id;//id is the field name, or the alias of the field, the following is the same as
$title =$row->title;
$asker=$row->asker;
For returning multiple results, you can do the following:
while($row=mysql_fetch_object($rs)){
$id=$row->id;
$ title=$row->title;
$asker=$row->asker;
}
Of course there are ways to make the returned result an array, and access can also be done Access according to the position index value of the field. You can query the relevant manual for this, but I will not introduce it here.
15. If you use an HTML online editor in your project, then FCKEditor may be a good choice. You can download FCKEditor online. There are many places to download it. Let me introduce the calling method:
First, install FCKEditor directory in the root directory of the website. Suppose you want to reference FCKEditor in edit.php in the /modules/cms/ directory of the website root directory. The specific code is as follows:
$sBasePath = "../../fckeditor/";//fckeditor is the directory of FCKEditor
$ oFCKeditor = new FCKeditor('content') ;
$oFCKeditor->BasePath= $sBasePath ;
$oFCKeditor->Value="" ;
$oFCKeditor->Width="666px";
$oFCKeditor->Height="300px"
?>
Create();?>
16. How to store data in session?
First of all, the session mechanism must be started. In addition to certain settings for apache itself, in the PHP page that uses session, the session_start() method must be called first, indicating that session is used on this page. The specific way to store data in the session is as follows:
session_start ();
$username="admin";
session_register("username");
?>
[code]
Then on other pages, you want to get the user in the session name, as follows:
[code]
$username=$_SESSION["username"];
?>
Similarly, you need Determining whether the currently visiting user has logged in can also be done in the above way: after the user logs in, register the user name in the session, and add the judgment to the PHP page that needs session control, for example:
if(!session_is_registered("username")){
header("Location:login.php");
}
The above is achieved by determining whether the username variable is registered in the session.
17. How to define classes and their member attributes and operations in PHP, and how to call them?
A direct example should illustrate the above problem:
Define a string processing tool class: StringUtils
class StringUtils{
function StringUtils(){
}
function getLength($str){
return strlen($str);
}
}
?>
The calling method in the php page is:
include 'classes/com/xxx/StringUtils.php';
$length=StringUtils::getLength("abcde");
//Or
$instance=new StringUtils;
$length=$instance->getLength("abcde");
?>
For a class method , generally there are two calling methods, one is to call it as a static method through the :: connector, and the other is to call it as an instance method through the -> connector. Although the call can be called in two ways, in practice, whether a method of a class is a static method is often logically defined. Therefore, each method is often called only in a certain way, such as a method in a service class. , basically all should be instance methods, and the methods in a tool class are basically all class methods or static methods, for example:
class UserService{
var $dbhost = "";
var $dbuser = "";
var $dbpw = " ";
var $dbname = "";
function UserService(){
}
function login($username,$password){
$link = mysql_connect($this-> dbhost, $this->dbuser, $this->dbpw) or die("Could not connect: ".mysql_error());
mysql_select_db($this->dbname);
$rs= mysql_query("select count(*) as value from cieqas_users where userid='".$username."' and password='".$password."'");
$row=mysql_fetch_object($rs);
$value=$row->value;
mysql_close($link);
settype($value,"integer");
if($valuereturn false;
}
return true;
}
?>
In addition, calling $this in the instance method has actual meaning.
18. How to set the type of a variable?
PHP can be regarded as a weakly typed language, which does not require mandatory type definition of variables, for example:
$username="admin";
$length=0;
$obj= new MyClass;
Many times, it is necessary to convert a string variable into an int variable, or vice versa, etc. How to do this? In fact, you can use the settype method, which can specify the type of the variable. The signature is as follows:
settype(var,type)
The type values include boolean (bool), integer (int), float, string, array, object, null
For example:
$state="0";
settype($state,"int");
if($state==0){
...
}
19. How to reverse an array?
Achieved through the array_reverse method, for example:
$arr=array();
$arr[0]=1;
$arr[1]=2;
$arr2=array_reverse($arr);
20, how to convert a Is the time displayed correctly?
In php, the time() method returns the number of seconds since the Unix new era (00:00:00, January 1, 1970, Greenwich Mean Time) to the current time. Then how to display the time correctly as a local correct one? Time, many times we use the setLocale method in php to specify the current region, but we often cannot get the correct time. I would like to introduce another solution to you, which is to solve it by combining Javascript with php, for example:
var time="";
var time=parseInt(time);
var date=new Date(time*1000);
var pattern="yyyy-MM-dd hh:mm:ss";
var df=new SimpleDateFormat( );
var str=df.format(date);
document.write(str);
Therefore, you can pass the value of time() in PHP to Javascript as a parameter of the Date object, and then process it through the Javascript open source class library JsJava.
21. PHP is a very popular language today. So far, a large number of function libraries have been formed, such as string processing, mathematics, XML, file, SOAP, network, etc. However, there are still some deficiencies in object-oriented aspects. However, it does not mean that it must be object-oriented to be considered a language. However, in actual website or project development, sometimes it is just a large number of function libraries. It doesn’t feel particularly convenient, especially sometimes when the business requires us to abstract the architecture level and each object. At this time, it is more appropriate to define a suitable business class library. After all, when we face development at a higher business level, We need a higher level of encapsulation, so classes and objects are on the agenda at this time. However, currently using various functions of PHP feels very convenient and very powerful. This makes me somewhat complain about Java-oriented In the language of objects, any logic must be implemented with the help of a lot of classes. It seems that languages need to learn from each other instead of attacking each other. Solving problems and promoting the development of the industry and society is the most fundamental.

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

Implementing an array sliding window in PHP can be done by functions slideWindow and slideWindowAverage. 1. Use the slideWindow function to split an array into a fixed-size subarray. 2. Use the slideWindowAverage function to calculate the average value in each window. 3. For real-time data streams, asynchronous processing and outlier detection can be used using ReactPHP.

The __clone method in PHP is used to perform custom operations when object cloning. When cloning an object using the clone keyword, if the object has a __clone method, the method will be automatically called, allowing customized processing during the cloning process, such as resetting the reference type attribute to ensure the independence of the cloned object.

In PHP, goto statements are used to unconditionally jump to specific tags in the program. 1) It can simplify the processing of complex nested loops or conditional statements, but 2) Using goto may make the code difficult to understand and maintain, and 3) It is recommended to give priority to the use of structured control statements. Overall, goto should be used with caution and best practices are followed to ensure the readability and maintainability of the code.

In PHP, data statistics can be achieved by using built-in functions, custom functions, and third-party libraries. 1) Use built-in functions such as array_sum() and count() to perform basic statistics. 2) Write custom functions to calculate complex statistics such as medians. 3) Use the PHP-ML library to perform advanced statistical analysis. Through these methods, data statistics can be performed efficiently.

Yes, anonymous functions in PHP refer to functions without names. They can be passed as parameters to other functions and as return values of functions, making the code more flexible and efficient. When using anonymous functions, you need to pay attention to scope and performance issues.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
