Revised version of 21 FAQ for PHP beginners

  • 2020-03-31 20:33:58
  • OfStack

1. How to connect two strings?
Answer: concatenating two strings in PHP can be done directly using the. Operation symbol, such as $newStr="Zhang"." SAN ".
2. How to calculate the length of a string?
A: $STR = "test"; The $length = strlen ($STR); Use the strlen(STR) function.
3. How to split a string by a separator?
Answer: use explodes (delim, STR) functions, such as $arr = explodes (" : : ", "a: : BDF: : DFSDF"); This function returns an array. You can use the split function of a String object in Java.
4. How to get the parameter value in the HTTP request?
Answer: for a GET request, use $_GET[paramName], and for a POST request, use $_POST[paramName], for example: $email=$_POST["usermail"].
5. Can PHP use classes like Java?
A: yes, but the mechanism and use may be different.
6. Can you give an example of using a for loop?
A:
 
for($i=0;$i<100;$i++){ 
echo $i; 
} 

7. How do I get variables in PHP from javascript?
A: examples are as follows:
 
<?php 
$username=$_POST["username"]; 
?> 
<script> 
var username="<?php echo $username ?>"; 
</script> 

8. How to delete a file?
Answer: using the unlink(filename) function, of course the program must have permission to delete the file, the PHP virtual space we are using may be on one
These files are restricted, so permission errors may occur.
9, I define a class User, declare a method of the class getName(), why I use $User =new User; $name=$user.getname () will report an error?
Answer: notice how class members are referenced in PHP. The above reference should be $name=$user-> GetName (), using -> Sign instead of
The ". "sign used in Java.
10. I applied for a PHP virtual space without mysql support. How can I access the application data?
A: you don't have to use a database to access data. A file system is fine, and even if you use a database, you don't have to use something like mysql
, oracle, such a database, you can also use some text database, such as TXTSQL, so that you do not have to rent expensive mysql
Database space.
11. I applied for a PHP space without database. Now my application data is stored in the file, but there will be a security problem, namely
Visitors can see the contents of these files from the url. How can I protect the contents of these files?
A: there are three suggested ways:
1) if you're renting PHP space that allows you to set HTTP access to directories, just set it up.
2) the contents of the file can be encrypted, so that even if downloaded, there is not much value.
3) you can change the suffix of these files to.php, which USES the PHP file to store application information, so that visitors cannot access it over HTTP
The actual contents of these files, of course, must be in the correct PHP syntax, and the content must use the hidden syntax of PHP syntax
Hide information, such as a file that holds account information:
Users. PHP
 
<?php 
 
?> 

12. How do I transcode a string?
Using PHP's iconv function, the signature is:
$STR = iconv (fromEncode toEncode, STR);
Such as:
$STR =" PHP string transcode ";
$STR = iconv (" utf-8 ", "GBK", $STR); // converts the string from utf-8 format to GBK format
Transcoding is an important issue. For example, many of the RSS feeds currently provided by blogs are 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 a file in PHP is similar to the concept of a file stream in Java. Many file read functions accept input streams not only from the local file system, but also from network files.
 
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 facilitate beginners to get started with the operation of mysql, 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); 
...//Here is the database operation, the following examples do not write database connection and close operations
mysql_close($link); 

2) insert new data into the table
Mysql_query (" insert into mytable (id, name) values (' ". $id. "', '". $name."') ");
Above, insert a piece of data into the id and name fields of the mytable table.
3) query the 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 the select clause, the following version of mysql3.22 is not supported, so many times PHP will not get results when writing complex SQL, which is not the fault of PHP, but the lower version of mysql.
6) for the result set returned by select, you can do the following:
To return a result, you can:
 
$row=mysql_fetch_object($rs); 
$id=$row->id;//The id is the name of the field, or the alias of the field, as follows
$title=$row->title; 
$asker=$row->asker; 

For multiple results returned, the following can be used:
 
while($row=mysql_fetch_object($rs)){ 
$id=$row->id; 
$title=$row->title; 
$asker=$row->asker; 
} 

Of course, there are methods to return the result as an array, access can also be accessed according to the position of the field index value, this can query the relevant manual, I will not cover.
15. If you use HTML online editor in your project, FCKEditor may be a good choice. FCKEditor can be downloaded on the Internet by yourself.
First, put the FCKEditor directory into the root directory of the website. Suppose you want to refer to FCKEditor in /modules/ CMS/edit. PHP in the root directory of the website.
 
<?php 
$sBasePath = "../../fckeditor/";//Fckeditor is the directory of fckeditor
$oFCKeditor = new FCKeditor('content') ; 
$oFCKeditor->BasePath= $sBasePath ; 
$oFCKeditor->Value="" ; 
$oFCKeditor->Width="666px"; 
$oFCKeditor->Height="300px" 
?> 
<div> 
<?php $oFCKeditor->Create();?> 
</div> 

16. How to store data in session?
To start the session mechanism, in addition to apache itself to do certain Settings, in the use of session PHP page, to call session_start() method, means that the use of session in this page. The specific way to store data in session is as follows:
 
<?php 
session_start(); 
$username="admin"; 
session_register("username"); 
?> 
[code] 
 So on other pages, you want to get session , as follows:  
[code] 
<?php 
$username=$_SESSION["username"]; 
?> 

Similarly, to determine whether the currently visiting user is logged in, the above method can also be used: after the user logs in, register the user name in the session, and add the judgment in the PHP page that requires session control, for example:
 
if(!session_is_registered("username")){ 
header("Location:login.php"); 
} 

This is done by determining whether the username variable is registered in the session.
17. How to define and invoke a class and its member properties and operations in PHP?
A direct example should illustrate the above problem:
Define a string handling utility class: StringUtils
 
<?php 
class StringUtils{ 
function StringUtils(){ 
} 
function getLength($str){ 
return strlen($str); 
} 
} 
?> 

The method of calling in the PHP page is:
 
<?php 
include 'classes/com/xxx/StringUtils.php'; 
$length=StringUtils::getLength("abcde"); 
//or
$instance=new StringUtils; 
$length=$instance->getLength("abcde"); 
?> 

For a class method, there are generally two ways to call, one is called as a static method, through :: concatenation, one is called as an instance method, through -> Connector. Although calls can be used two ways to call, but in practice a class method for static methods that are often has defined on logic, so each method, tend to use some way call, for example, a service class of methods, basically should be instance methods, and a tool of class methods, basically is a class method or static methods, such as:
 
<?php 
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; 
} 
?> 

Also, calling $this in an instance method makes sense.
18. How to set the type of a variable?
PHP can be counted as a weakly typed language that does not require a mandatory type definition of a variable, such as:
$username = "admin";
The $length = 0;
$obj = new MyClass;
Many times you need to convert a string variable to an int, or vice versa, etc. How do you do that? In fact, you can use the settype method, which can specify the type of the variable. The signature is as follows:
Settype (var, type)
Values of type are Boolean (bool), integer(int), float, string, array, object, null
Such as:
$state = "0";
Settype ($state, "int");
If ($state = = 0) {
.
}
19. How do I reverse an array?
Through the array_reverse method, for example:
 
$arr=array(); 
$arr[0]=1; 
$arr[1]=2; 
$arr2=array_reverse($arr); 

20. How to display a time correctly in PHP?
In PHP by time () method returns the new era since the Unix (GMT 00:00:00) on January 1, 1970 to the current number of seconds, then how will this time the correct display for local time correctly, many times we all use in PHP setLocale method, specify the area, but we are not the right time, to introduce a other solution, is to solve combining Javascript and PHP, such as:
 
var time="<?php echo 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 handle it through the Javascript open source class library JsJava.
21, PHP is very popular in today's language, so far, have formed a large number of libraries, such as processing of the string, mathematics, files, XML and SOAP, network, etc., but its in terms of object-oriented, and the lack of a certain degree, however, is not to say don't want to know how object-oriented can be regarded as a language, in the actual site or project development, however, sometimes feeling is not just a lot of function library special convenient, especially in some cases, the business we need to abstract the architectural layers, and each object, This time defines a set of appropriate business class library is more appropriate, after all, when we are faced with higher level of business development, we need to encapsulate level higher, so when the classes and objects on the agenda, but currently use PHP to each function, feel is also very convenient, and very strong, and it makes me a bit complains that object-oriented languages like Java, what logic is to use a lot of classes, it seems that language is the need to learn from each other between, not attack each other, to solve the problem that it is essential to promote the development of industry and society.

Related articles: