


PHP returns the data array taken from the database using the specified field as the index_PHP Tutorial
In many cases, from the time we are exposed to a new project to the completion of development, we then go back and carefully browse the codes we have written. Many of them are codes that we have used proficiently before. Therefore, when completing each new project, do some project summary and code summary appropriately. Maybe you will use it in future projects, and you are very likely to get unexpected gains, such as code optimization and better ideas. , faster implementation methods, etc.
Sometimes what makes a great program developer is not the amount of code, but the simplicity of the program code, the complexity of the logic but the convenience of implementation. These are the things that show whether a programmer is a good programmer. We don’t want to be programmers who work overtime day and night until late at night, scrambling to write a large amount of code!
This article will share with you some PHP programming skills. Some of them were learned when looking at other people’s codes, and some were summarized by myself.
Using a specific field as an index, return the data array fetched from the database
It is easier to give an example:
If you want to count the traffic of a specified site from other websites, And make a small backend to check the traffic brought by each website every day. We first build 2 data tables:
Table 1. Site configuration table (only counts the traffic of these websites)
CREATE TABLE `site_config` (
`id` smallint(5) unsigned NOT NULL auto_increment COMMENT 'primary key, auto-increment',
`sid` smallint(5) unsigned NOT NULL COMMENT ' Website ID',
`site_url` varchar(128) NOT NULL COMMENT 'Website URL address',
`site_name` varchar(80) NOT NULL COMMENT 'Website name',
`add_time` timestamp NOT NULL default CURRENT_TIMESTAMP COMMENT 'Add time',
PRIMARY KEY (`id`),
UNIQUE KEY `adid` (`sid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Site configuration table' ;
Table 2, site traffic statistics table (one record per user)
CREATE TABLE `site_stat` (
`id` int(11) unsigned NOT NULL auto_increment COMMENT 'primary key, auto-increment',
`sid` smallint(5) unsigned NOT NULL COMMENT 'website ID',
`ip_address` varchar(32) NOT NULL COMMENT 'User IP',
`add_time` timestamp NOT NULL default CURRENT_TIMESTAMP COMMENT 'Add time',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Site traffic statistics table';
Because the site_config table read operations are greater than the write operations, the type is set to MyISAM; and the site_stat table write operations are greater than the read operations , therefore, I set the table type to InnoDB. (These are also things you need to consider when designing data, and the speed will be improved a lot).
Back to the topic, if there are several pieces of data in the table site_config:
The data format is: id, sid, site_url, add_time
1,200,baidu.com,2013-06-30 14:20:00
2,201,google.com,2013-06-30 14:20:00
3,202,cnblogs.com,2013-06-30 14:20:00
4,203,codejia.net,2013-06 -30 14:20:00
Some data has been generated in the site traffic statistics table site_stat, as follows:
The data format is: id, sid, ip_address, add_time
1,200,167.87.32.4,2013-06-30 14:40:00
2,200,192.168.11.56,2013-06-30 14:40:10
3,202,167.87.32.4,2013-06-30 14:40:10
4,202,192.168.11.56, 2013-06- 30 14:40:20
5,203,167.87.32.4,2013-06-30 14:40:20
6,202,10.10.10.10,2013-06-30 14:40:30
7,200,167.87.32.4,2 013 -06-30 14:40:31
The report format you need to do in the background is: date, website ID, website URL, traffic number (sites with no traffic will also be displayed, and the traffic will be displayed as 0)
You You may think of left joining the table site_config according to the sid group by in the table site_stat based on the date. This is obviously not the method I will share.
Use 2 SQLs to do it, one is to get all sites; the other is to get site traffic statistics on a specified date.
SQL1 gets all sites:
SELECT sid,site_url,site_name FROM site_config
SQL2 to get site statistics (if it is today):
SELECT sid,COUNT(1) AS come_total FROM site_stat
WHERE add_time>='2013-06-30 00:00:00'
AND add_time<='2013-06-30 23:59:59 '
GROUP BY sid
A lot of what I said earlier is to pave the way for what follows. Let me share a PHP method that uses the passed field as an index to return a two-dimensional array:
protected function getList($sql,$filed = null){
$res = mysql_query($sql,$this->link_sc);
$data = array();
if($filed === null){
while($row = mysql_fetch_assoc($res)){
$data[] = $row;
}
}else{
while($row = mysql_fetch_assoc($res)){
$data[$row[$filed]] = $row;
}
}
return $data;
}
Pass in your SQL and the fields that need to be indexed. The premise is that the fields passed in must be among the fields returned by select.
We do not need to pass the past field when fetching all sites, but when fetching site traffic statistics, we pass the site sid, which is as follows:
$sites = getList($sql1); //All sites
$data = getList($sql2,'sid'); //Site traffic Data, returns a two-dimensional array with sid as the index
Finally, when displaying the report, use foreach to loop $sites, and when fetching traffic, go to the array $data to get the data with the index sid. .
Very convenient and easy to master, I do it often.
Finally, take a look at the statistical results report in the above table:
The format is: date, website ID, website URL, traffic number
2013-06-30,200,baidu.com,3
2013 -06-30,201,google.com,0
2013-06-30,202,cnblogs.com,3
2013-06-30,203,codejia.net,1
Summary: It seems that writing so much means that It’s a small trick, but don’t underestimate it, it can save you a lot of time. Therefore, everyone should summarize more when writing code, come to the blog park to communicate and learn with everyone, and your programming level will definitely improve quickly!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
