search
HomeDatabaseMysql TutorialPHP中操作MySQL的需注意的问题_MySQL

  1.每一行命令都是用分号 (;) 作为结束

  对于 MySQL ,第一件你必须牢记的是它的每一行命令都是用分号 (;) 作为结束的,但……没有完全绝对的事,在这儿也是一样,当一行 MySQL 被插入在 PHP 代码中时,最好把后面的分号省略掉,例如:

mysql_query ("INSERT INTO tablename (first_name, last_name) VALUES ('$first_name', $last_name')");

  这是因为 PHP 也是以分号作为一行的结束的,额外的分号有时会让 PHP 的语法分析器搞不明白,所以还是省略掉的好。在这种情况下,虽然省略了分号,但是 PHP 在执行 MySQL 命令时会自动的帮你加上的。

  另外还有一个不要加分号的情况。当你想把要字段的竖者排列显示下来,而不是像通常的那样横着排列时,你可以用 G 来结束一行 SQL 语句,这时就用不上分号了,例如:

SELECT * FROM PENPALS WHERE USER_ID = 1G

  2. TEXT、DATE、和 SET 数据类型

  MySQL 数据表的字段必须有定义一个数据类型。这有大约 25 种选择,大部分都是直接明了的,就不多费口舌了。但有几个有必要提一下。

  TEXT 不是一种数据类型,虽然可能有些书上是这么说的。它实际上应该是“ LONG VARCHAR ”或者“ MEDIUMTEXT ”。

  DATE 数据类型的格式是 YYYY-MM-DD ,比如: 1999-12-08 。你可以很容易的用 date 函数来得到这种格式的当前系统时间: date("Y-m-d")

  并且,在 DATA 数据类型之间可以作减法,得到相差的时间天数:

$age = ($current_date - $birthdate);

  集合 SET 是一个有用的数据类型,它和枚举 ENUM 有点相似,只不过是 SET 能够保存多个值而 ENUM 只能保存一个值而已。而且, SET 类型最多只能够有 64 个预定的值,而 ENUM 类型却能够处理最多 65,535 个预定义的值。而如果需要有大于 64 个值的集合,该怎么办呢?这时就需要定义多个集合来一起解决这个问题了。

  3. 通配符

  SQL 的通配符有两种:“ * ”和“ % ”。分别用在不同的情况下。例如:如果你想看到数据库的所有内容,可以像这样来查询:

SELECT * FROM dbname WHERE USER_ID LIKE '%';

  这儿,两个通配符都被用上了。他们表示相同的意思 ?? 都是用来匹配任何的字符串,但是他们用在不同的上下文中。“ * ”用来匹配字段名,而“ % ”用来匹配字段值。另外一个不容易引起注意的地方是“ % ”通配符需要和 LIKE 关键字一起使用。

  还有一个通配符,就是下划线“ _ ”,它代表的意思和上面不同,是用来匹配任何单个的字符的。

  4. NOT NULL 和空记录

  如果用户在没有填任何东西的情况下按了 submit 按钮,会怎样呢?如果你确实需要一个值,那么可以用客户端脚本或者服务器端脚本来进行数据验证,这一点在前面已经说过了。但是,在数据库中却是允许一些字段被空出来什么也不填。对此类纪录, MySQL 将要为之执行一些事情:插入值 NULL ,这是缺省的操作。

  如果你在字段定义中为之声明了 NOT NULL (在建立或者修改这个字段的时候), MySQL 将把这个字段空出来什么东西也不填。对于一个 ENUM 枚举类型的字段,如果你为之声明了 NOT NULL , MySQL 将把枚举集的第一个值插入到字段中。也就是说, MySQL 把枚举集的第一个值作为这个枚举类型的缺省值。

  一个值为 NULL 的纪录和一个空纪录是有一些区别的。 % 通配符可以匹配空纪录,但是却不能匹配 NULL 纪录。在某些时候,这种区别会造成一些意想不到的后果。就我的经验而言,任何字段都应该声明为 NOT NULL 。这样下面的 SELECT 查询语句就能够正常运转了:

if (!$CITY) {$CITY = "%";}

$selectresult = mysql_query ("SELECT * FROM dbname

WHERE FIRST_NAME = ' 柳 '

AND LAST_NAME = ' 如风 '

AND CITY LIKE '$CITY'

");

  在第一行中,如果用户没有指定一个 CITY 值,那么就会用通配符 % 来代入 CITY 变量,这样搜索时就会把任何的 CITY 值都考虑进去,甚至包括那些 CITY 字段为空的纪录。

  但是如果有一些纪录,它的 CITY 字段值是 NULL ,这时问题就出现了。上面的查询是不能够找到这些字段的。问题的一个解决办法可以是这样:

if (!$CITY) { $CITY = "%"; }

$selectresult = mysql_query ("SELECT * FROM dbname

WHERE FIRST_NAME = ' 柳 '

AND LAST_NAME = ' 如风 '

AND (CITY LIKE '$CITY' OR CITY IS NULL)

");

  注意在搜索 NULL 时,必须用“ IS ”关键字,而 LIKE 时不会正常工作的。

  在最后要提到的是,如果你在加入或者修改一个新的字段之前,数据库中已经有了一些记录了,这时新加入的字段在原来的纪录中的值,可能是 NULL ,也可能为空。这也算是 MySQL 的一个 Bug 吧,所以在这种情况下,使用 SELECT 查询要特别的小心。

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
How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL Commands in MySQL: Practical ExamplesSQL Commands in MySQL: Practical ExamplesApr 14, 2025 am 12:09 AM

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

How does InnoDB handle ACID compliance?How does InnoDB handle ACID compliance?Apr 14, 2025 am 12:03 AM

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment