Home php教程 php手册 PHP开发者常犯的10个MySQL错误

PHP开发者常犯的10个MySQL错误

Jun 06, 2016 pm 07:46 PM
mysql php Developer database mistake

数据库是Web大多数应用开发的基

数据库是Web大多数应用开发的基础。如果你是用PHP,那么大多数据库用的是MySQL也是LAMP架构的重要部分。PHP看起来很简单,一个初学者也可以几个小时内就能开始写函数了。但是建立一个稳定、可靠的数据库确需要时间和经验。下面就是一些这样的经验,不仅仅是MYSQL,其他数据库也一样可以参考。

1.使用MyISAM而不是InnoDB
MySQL有很多的数据库引擎,单一般也就用MyISAM和InnoDB。
MyISAM 是默认使用的。但是除非你是建立一个非常简单的数据库或者只是实验性的,那么到大多数时候这个选择是错误的。MyISAM不支持外键的约束,这是保证数据完整性的精华所在啊。另外,MyISAM会在添加或者更新数据的时候将整个表锁住,这在以后的扩展性能上会有很大的问题。
解决办法很简单:使用InnoDB。
2.使用PHP的mysql方法
PHP从一开始就提供了MySQL的函数库。很多程序都依赖于mysql_connect、mysql_query、mysql_fetch_assoc等等,但是PHP手册中建议:
如果你使用的MySQL版本在4.1.3之后,那么强烈建议使用mysqli扩展。
mysqli,或者说MySQL的高级扩展,有一些优点:
有面向对象的接口
prepared statements(预处理语句,可以有效防止SQL-注入攻击,还能提高性能)
支持多种语句和事务
另外,如果你想支持多数据库那么应该考虑一下PDO。
3.不过滤用户输入
应该是:永远别相信用户的输入。用后端的PHP来校验过滤每一条输入的信息,不要相信Javascript。像下面这样的SQL语句很容易就会被攻击:
$username = $_POST["name"];
$password = $_POST["password"];
$sql = "SELECT userid FROM usertable WHERE username=?$username?AND password=?$password?;"; // run query...
这样的代码,如果用户输入”admin’;”那么,就相当于下面这条了:
SELECT userid FROM usertable WHERE username=?admin?;
这样入侵者就能不输入密码,就通过admin身份登录了。
4.不使用UTF-8
那些英美国家的用户,很少考虑语言的问题,这样就造成很多产品就不能在其他地方通用。还有一些GBK编码的,也会有很多的麻烦。
UTF-8解决了很多国际化的问题。虽然PHP6才能比较完美的解决这个问题,但是也不妨碍你将MySQL的字符集设置为UTF-8。
5.该用SQL的地方使用PHP
如果你刚接触MySQL,有时候解决问题的时候可能会先考虑使用你熟悉的语言来解决。这样就可能造成一些浪费和性能比较差的情况。比如:计算平均值的时候不适用MySQL原生的AVG()方法,而是用PHP将所有值循环一遍然后累加计算平均值。
另外还要注意SQL查询中的PHP循环。通常,在取得所有结果之后再用PHP来循环的效率更高。
一般在处理大量数据的时候使用强有力的数据库方法,更能提高效率。
6.不优化查询
99%的PHP性能问题都是数据库造成的,一条糟糕的SQL语句可能让你的整个程序都非常慢。MySQL的EXPLAIN statement,Query Profiler,many other tools的这些工具可以帮你找出那些调皮的SELECT。
7.使用错误的数据类型
MySQL提供一系列数字、字符串、时间等的数据类型。如果你想存储日期,那么就是用DATE或者DATETIME类型,使用整形或者字符串会让事情更加复杂。
有时候你想用自己定义的数据类型,例如,使用字符串存储序列化的PHP对象。数据库的添加可能很容易,但是这样的话,MySQL就会变得很笨重,而且以后可能导致一些问题。
8.在SELECT查询中使用*
不要使用*在表中返回所有的字段,这会非常的慢。你只需要取出你需要的数据字段。如果你需要取出所有的字段,那么可能你的表需要更改了。
9.索引不足或者过度索引
一般来说,应该索引出现在SELECT语句中WHERE后面所有的字段。
例如,假如我们的用户表有一个数字的ID(主键)和email地址。登录之后,MySQL应该通过email找到相应的ID。通过索引,MySQL可以通过搜索算法很快的定位email。如果没有索引,MySQL就需要检查每一项记录直到找到。
这样的话,你可能想给每一个字段都添加索引,但是这样做的后果就是在你更新或者添加的时候,索引就会重新做一遍,当数据量大的时候,就会有性能问题。所以,只在需要的字段做索引。
10.不备份
也许不常发生,但是数据库损毁,硬盘坏了、服务停止等等,这些都会对数据造成灾难性的破坏。所以你一定要确保自动备份数据或者保存副本。
11.另外:不考虑其他数据库
MySQL可能是PHP用的最多的数据库了,但是也不是唯一的选择。 PostgreSQL和Firebird也是竞争者,他们都开源,而且不被某些公司所控制。微软提供SQL Server Express,Oracle有10g Express,这些企业级的也有免费版。SQLite对于一些小型的或者嵌入式应用来说也是不错的选择。

http://www.cnbeta.com/articles/169770.htm

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Redis: Understanding Its Architecture and Purpose Redis: Understanding Its Architecture and Purpose Apr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

MongoDB's Future: The State of the Database MongoDB's Future: The State of the Database Apr 25, 2025 am 12:21 AM

MongoDB's future is full of possibilities: 1. The development of cloud-native databases, 2. The fields of artificial intelligence and big data are focused, 3. The improvement of security and compliance. MongoDB continues to advance and make breakthroughs in technological innovation, market position and future development direction.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles