Home Database Mysql Tutorial MySQL编程中的6个重要的实用技巧_MySQL

MySQL编程中的6个重要的实用技巧_MySQL

May 30, 2016 pm 05:09 PM
mysql

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

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

1

<ol class="dp-j"><li class="alt"><span><span>mysql_query(</span><span class="string">"INSERT INTO tablename(first_name,last_name)VALUES('$first_name',$last_name')"</span><span>); </span></span></li></ol>

Copy after login

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

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

看下面的例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<ol class="dp-j">

<li class="alt"><span><span>$connection=mysql_connect(</span><span class="string">"localhost"</span><span>,</span><span class="string">"albert"</span><span>,</span><span class="string">"shhh"</span><span>); </span></span></li>

<li><span> </span></li>

<li class="alt"><span>mysql_select_db(<span class="string">"winestore"</span><span>,$connection); </span></span></li>

<li><span> </span></li>

<li class="alt"><span>$result=mysql_query("SELECT cust_id,surname, </span></li>

<li><span> </span></li>

<li class="alt"><span>firstname FROM customer",$connection); </span></li>

<li><span> </span></li>

<li class="alt"><span><span class="keyword">while</span><span>($row=mysql_fetch_array($result)) </span></span></li>

<li><span> </span></li>

<li class="alt"><span>{ </span></li>

<li><span> </span></li>

<li class="alt"><span>echo<span class="string">"ID:t{$row["</span><span>cust_id</span><span class="string">"]}n"</span><span>; </span></span></li>

<li><span> </span></li>

<li class="alt"><span>echo<span class="string">"Surnamet{$row["</span><span>surname</span><span class="string">"]}n"</span><span>; </span></span></li>

<li><span> </span></li>

<li class="alt"><span>echo<span class="string">"First name:t{$row["</span><span>firstname</span><span class="string">"]}nn"</span><span>; </span></span></li>

<li><span> </span></li>

<li class="alt"><span>} <br></span></li>

</ol>

Copy after login

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

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

1

<ol class="dp-j"><li class="alt"><span><span>SELECT winery.name AS wname,region.name AS rname,FROM winery,region WHERE winery.region_id=region.region_id; </span></span></li></ol>

Copy after login

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

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

1

2

3

4

5

<ol class="dp-j">

<li class="alt"><span><span>SELECT winery.region_id </span></span></li>

<li><span> </span></li>

<li class="alt"><span>FROM winery </span></li>

</ol>

Copy after login

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

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

1

2

3

4

5

<ol class="dp-j">

<li class="alt"><span><span>SELECT count(*) </span></span></li>

<li><span> </span></li>

<li class="alt"><span>FROM customer; </span></li>

</ol>

Copy after login

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

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

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

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

DATE数据类型的格式是YYYY-MM-DD,比如:1999-12-08。你可以很容易的用date函数来得到这种格式的当前系统时间:date(“Y-m-d”)并且,在DATA数据类型之间可以作减法,得到相差的时间天数:

1

<ol class="dp-j"><li class="alt"><span><span>$age=($current_date-$birthdate); </span></span></li></ol>

Copy after login

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

4.用mysql_unbuffered_query()开发快速的脚本

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

5.通配符

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

1

<ol class="dp-j"><li class="alt"><span><span>SELECT*FROM dbname WHERE USER_ID LIKE</span><span class="string">'%'</span><span>; </span></span></li></ol>

Copy after login

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

6.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查询要特别的小心。

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

PHP's big data structure processing skills PHP's big data structure processing skills May 08, 2024 am 10:24 AM

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the &quot;MySQL Native Password&quot; plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

The difference between oracle database and mysql The difference between oracle database and mysql May 10, 2024 am 01:54 AM

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.

See all articles