Home  >  Article  >  Backend Development  >  Collection of Frequently Asked Questions for PHP Beginners Revised Edition (21 Questions and Answers)_PHP Tutorial

Collection of Frequently Asked Questions for PHP Beginners Revised Edition (21 Questions and Answers)_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:40:07954browse

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:

Copy code The code is as follows:

for($i=0;$i<100;$ i++){
echo $i;
}

7. How to get variables in php in javascript?
Answer: An example is as follows:
Copy code The code 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

Copy code The code is as follows:
/*
:::user1:password1::user2:password2::user3: password3:::
*/
?>

12. How to transcode a string?
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:

Copy code The code is as follows:
function getRssContent($url){
$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
Copy code Code As follows:

$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:
Copy the code The code is as follows:

$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:
Copy code The code is as follows:

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:
Copy the code The 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();?>
< /div>

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:
Copy code The code 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:
Copy code The code is as follows:

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
Copy code The code is as follows:

class StringUtils{
function StringUtils(){
}
function getLength($str){
return strlen($str);
}
}
?>

The calling method in the php page is:
Copy code Code As follows:

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:
Copy code The code is as follows:

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($value<=0){
return 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:
Copy code The code is as follows:

$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:
Copy code The code is as follows:

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321467.htmlTechArticle1. How to connect two strings? Answer: To connect two strings in PHP, you can directly use the "." operation symbol, such as $newStr="Zhang"."san". In Java, you use the "+" operation symbol,...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn