Home Backend Development PHP Tutorial 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

Jul 21, 2016 pm 03:40 PM
php use beginner Can exist how string common problem Genuine answer connect Q&A gather

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Summary of FAQs for DeepSeek usage Summary of FAQs for DeepSeek usage Feb 19, 2025 pm 03:45 PM

DeepSeekAI Tool User Guide and FAQ DeepSeek is a powerful AI intelligent tool. This article will answer some common usage questions to help you get started quickly. FAQ: The difference between different access methods: There is no difference in function between web version, App version and API calls, and App is just a wrapper for web version. The local deployment uses a distillation model, which is slightly inferior to the full version of DeepSeek-R1, but the 32-bit model theoretically has 90% full version capability. What is a tavern? SillyTavern is a front-end interface that requires calling the AI ​​model through API or Ollama. What is breaking limit

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles