Home php教程 php手册 PHP和MySQL开发的8个技巧

PHP和MySQL开发的8个技巧

Jun 06, 2016 pm 07:52 PM
mysql php use develop Skill array

1. PHP 中数组的使用 在操作 数据库 时,使用关联数组( associatively-indexed arrays )十分有帮助,下面我们看一个基本的数字格式的数组遍历: ?php $temp[0] = "richmond"; $temp[1] = "tigers"; $temp[2] = "premiers"; for($x=0;$xcount($temp);$x++)

1. PHP 中数组的使用
在操作
数据库时,使用关联数组(associatively-indexed arrays)十分有帮助,下面我们看一个基本的数字格式的数组遍历:

  

 $temp[0] = "richmond";

 $temp[1] = "tigers";

$temp[2] = "premiers";

 

 for($x=0;$x

 {

      echo $temp[$x];

     echo " ";

}

 ?>

 

然而另外一种更加节省代码的方式是:

 

     $temp = array("richmond", "tigers", "premiers");

      foreach ($temp as $element)

      echo "$element ";

 ?>

 

foreach 还能输出文字下标:

 

      $temp = array("club" => "richmond",

      "nickname" =>"tigers",

      "aim" => "premiers");

 

       foreach ($temp as $key => $value)

       echo "$key : $value ";

?>

 

PHP 手册中描述了大约 50 个用于处理数组的函数。

2. 
PHP 字符串中加入变量

这个很简单的:

     $temp = "hello"

     echo "$temp world";

?>

 

但是需要说明的是,尽管下面的例子没有错误:

 

      $temp = array("one" => 1, "two" => 2);

       // 输出:: The first element is 1

      echo "The first element is $temp[one].";

?>

 

但是如果后面那个 echo 语句没有双引号引起来的话,就要报错,因此建议使用花括号:

      $temp = array("one" => 1, "two" => 2);

       echo "The first element is {$temp["one"]}.";

?>

 

3. 采用关联数组存取查询结果
看下面的例子:

   $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 "Surname\t{$row["surname"]}\n";

   echo "First name:\t{$row["firstname"]}\n\n";

 }

 ?>

 

函数 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(*)"]

4. 
注意常见的 PHP bug

常见的 PHP 纠错问题是:

No page rendered by the Web browser when much more is expected
A pop-up dialog stating that the "Document Contains No Data"
A partial page when more is expected

出现这些情况的大多数原因并不在于脚本的逻辑,而是 HTML 中存在的 bug 或者脚本生成的 HTML  bug 。例如缺少类似  之类的关闭 Tag,页面就不能刷新。解决这个问题的办法就是,查看 HTML 的源代码。

对于复杂的,不能查到原因的页面,可以通过 W3C 的页面校验程序 
http://validator.w3.org/ 来分析。

如果没有定义变量,或者变量定义错误也会让程序变得古怪。例如下面的死循环:

        for($counter=0; $counter

       myFunction();

 ?>

 

变量 $Counter 在增加,而 $counter 永远小于 10。这类错误一般都能通过设置较高的错误报告级别来找到:

     error_reporting(E_ALL);

 

      for($counter=0; $counter

     myFunction();

?>

 

5. 采用 header() 函数处理单部件查询

在很多 Web 数据库应用中,一些功能往往让用户点击一个连接后,继续停留在当前页面,这样的工作我叫它单部件查询

下面是一个叫做 calling.php 的脚本:

  

 

Calling page example

 

Click here!

 

当用户点击上面的连接时,就去调用 action.php。下面是 action.php 的源码:

 

      // 数据库功能

      // 重定向

     header("Location: $HTTP_REFERER");

     exit;

?>

 

这里有两个常见的错误需要提醒一下:
调用 header() 函数后要包含一个 exit 语句让脚本停止,否则后续的脚本可能会在头发送前输出。


header() 
函数常见的一个错误是:
Warning: Cannot add header information - headers already sent...
header() 
函数只能在 HTML 输出之前被调用,因此你需要检查 php 前面可能存在的空行,空格等等。

6. reload 
的问题及其解决

我以前在写 PHP 程序时,经常碰到页面刷新时,数据库多处理一次的情况。
我们来看 addcust.php

 

       $query = "INSERT INTO customer

      SET surname = $surname,

        firstname = $firstname";

       $connection = mysql_connect("localhost", "fred", "shhh");

      mysql_select_db("winestore", $connection);

     $result = mysql_query($query, $connection);

?>

 /span>

  "-//W3C//DTD HTML 4.0 Transitional//EN"

 "http://www.w3.org/TR/html4/loose.dtd" >

  

 Customer insert

 

 I've inserted the customer for you.

  ?>

 

假设我们用下面的连接使用这个程序:

http://www.freelamp.com/addcust. ... &firstname=Fred

如果这个请求只提交一次,OK ,不会有问题,但是如果多次刷新,你就会有多条记录插入。
这个问题可以通过 header() 函数解决:下面是新版本的 addcust.php

     $query = "INSERT INTO customer

     SET surname = $surname,

     firstname = $firstname";

     $connection = mysql_connect("localhost", "fred", "shhh");

     mysql_select_db("winestore", $connection);

    $result = mysql_query($query, $connection);

     he

 

ader("Location: cust_receipt.php");
?>
这个脚本把浏览器重定向到一个新的页面:cust_receipt.php

  

  

 

Customer insert

  

 

 I've inserted the customer for you.

 

  

 

这样,原来的页面继续刷新也没有副作用了。

7. 
巧用锁机制来提高应用性能

如果我们要紧急运行一个报表,那么,我们可以对表加写锁,防治别人读写,来提高对这个表的处理速度。

8. 
mysql_unbuffered_query() 开发快速的脚本

这个函数能用来替换 mysql_query() 函数,主要的区别就是 mysql_unbuffered_query() 执行完查询后马上返回,不需要等待或者对数据库加锁。

但是返回的行数不能用mysql_num_rows() 函数来检查,因为输出的结果集大小未知。

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 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
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.

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.

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.

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.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

See all articles