search
HomeDatabaseMysql TutorialMySQL编程中的6个重要的实用技巧

对于MySQL,第一件你必须牢记的是它的每一行命令都是用分号(;)作为结束的,但当一行MySQL被插入在PHP代码中时,最好把后面的分号

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

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

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

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

采用关联数组存取查询结果

看下面的例子:

$connection=mysql_connect("localhost","albert","shhh"); mysql_select_db("winestore",$connection); $result=mysql_query("SELECT cust_id,surname, firstname FROM customer",$connection); while($row=mysql_fetch_array($result)) { echo"ID:t{$row["cust_id"]}n"; echo"Surnamet{$row["surname"]}n"; echo"First name:t{$row["firstname"]}nn"; }

函数mysql_fetch_array()把查询结果的一行放入数组,可以同时用两种方式引用,例如cust_id可以同时用下面两种方式:$row[“cust_id”]或者$row[0]。显然,前者的可读性要比后者好多了。

在多表连查中,如果两个列名字一样,最好用别名分开:

SELECT winery.name AS wname,region.name AS rname,FROM winery,region WHERE winery.region_id=region.region_id;

列名的引用为:$row[“wname”]和$row[“rname”]

在指定表名和列名的情况下,只引用列名:

SELECT winery.region_id FROM winery

列名的引用为:$row[“region_id”]

聚集函数的引用就是引用名:

SELECT count(*) FROM customer;

列名的引用为:$row[“count(*)”]

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个值的集合,该怎么办呢,这时就需要定义多个集合来一起解决这个问题了。

用mysql_unbuffered_query()开发快速的脚本

这个函数能用来替换mysql_query()函数,主要的区别就是mysql_unbuffered_query()执行完查询后马上返回,不需要等待或者对数据库加锁。但是返回的行数不能用mysql_num_rows()函数来检查,因为输出的结果集大小未知。

通配符

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

SELECT*FROM dbname WHERE USER_ID LIKE'%';

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

NOT NULL和空记录

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

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

一个值为NULL的纪录和一个空纪录是有一些区别的。%通配符可以匹配空纪录,但是却不能匹配NULL纪录。在某些时候,,这种区别会造成一些意想不到的后果。就我的经验而言,任何字段都应该声明为NOT NULL。这样许多的SELECT查询语句就能够正常运转了。注意在搜索NULL时,必须用“IS”关键字,而LIKE是不会正常工作的。在最后要提到的是,如果你在加入或者修改一个新的字段之前,数据库中已经有了一些记录了,这时新加入的字段在原来的纪录中的值,可能是NULL,也可能为空。这也算是MySQL的一个Bug吧,所以在这种情况下,使用SELECT查询要特别的小心。

--------------------------------------分割线 --------------------------------------

Ubuntu 14.04下安装MySQL

《MySQL权威指南(原书第2版)》清晰中文扫描版 PDF

Ubuntu 14.04 LTS 安装 LNMP Nginx\PHP5 (PHP-FPM)\MySQL

Ubuntu 14.04下搭建MySQL主从服务器

Ubuntu 12.04 LTS 构建高可用分布式 MySQL 集群

Ubuntu 12.04下源代码安装MySQL5.6以及Python-MySQLdb

MySQL-5.5.38通用二进制安装

--------------------------------------分割线 --------------------------------------

本文永久更新链接地址:

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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

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

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software