php 执行sql语句时 如果有错误,怎么做异常处理在前台友好显示呢?

解决方案 »

  1.   

    php数据库异常使用习惯了c#,java,在数据库异常时,使用try...catch就能方便的捕获异常。在使用php时就想当然的认为php5也能自动抛出异常,但是在实际开发过程中确实很失望,根本就不能捕获异常,无论是使用mysql还是mysqli扩展库,都不行。仔细分析一下,恍然大悟,php的扩展库是使用c开发的,而c语言根本就不支持异常,所有的错误都是根据返回的函数值来判断的,具体的错误信息采用额外的api函数来获取,这很类似于windows api的getlassterror函数,在php里我们可以使用mysql_errno和mysql_error来获取出错信息。
      

  2.   

    mysql_errno
    (PHP 4, PHP 5)mysql_errno — 返回上一个 MySQL 操作中的错误信息的数字编码 说明
    int mysql_errno ([ resource $link_identifier ] )
    返回上一个 MySQL 函数的错误号码,如果没有出错则返回 0(零)。 从 MySQL 数据库后端来的错误不再发出警告,要用 mysql_errno() 来提取错误代码。注意本函数仅返回最近一次 MySQL 函数的执行(不包括 mysql_error() 和 mysql_errno())的错误代码,因此如果要使用此函数,确保在调用另一个 MySQL 函数之前检查它的值。 
    Example #1 mysql_errno() 例子<?php
        mysql_connect("localhost", "mysql_user", "mysql_password");    mysql_select_db("nonexistentdb");
        echo mysql_errno() . ": " . mysql_error(). "\n";    mysql_select_db("kossu");
        mysql_query("SELECT * FROM nonexistenttable");
        echo mysql_errno() . ": " . mysql_error() . "\n";
    ?> 
    以上例子将产生如下输出: 1049: Unknown database 'nonexistentdb'
    1146: Table 'kossu.nonexistenttable' doesn't existNote: 如果指定了可选参数则用给定的连接提取错误代码。否则使用上一个打开的连接。 
      

  3.   

    mysql_error
    (PHP 4, PHP 5)mysql_error — 返回上一个 MySQL 操作产生的文本错误信息 说明
    string mysql_error ([ resource $link_identifier ] )
    返回上一个 MySQL 函数的错误文本,如果没有出错则返回 ''(空字符串)。如果没有指定连接资源号,则使用上一个成功打开的连接从 MySQL 服务器提取错误信息。 从 MySQL 数据库后端来的错误不再发出警告,要用 mysql_error() 来提取错误文本。注意本函数仅返回最近一次 MySQL 函数的执行(不包括 mysql_error() 和 mysql_errno())的错误文本,因此如果要使用此函数,确保在调用另一个 MySQL 函数之前检查它的值。 
    Example #1 mysql_error 例子<?php
        mysql_connect("localhost", "mysql_user", "mysql_password");    mysql_select_db("nonexistentdb");
        echo mysql_errno() . ": " . mysql_error(). "\n";    mysql_select_db("kossu");
        mysql_query("SELECT * FROM nonexistenttable");
        echo mysql_errno() . ": " . mysql_error() . "\n";
    ?> 
    以上例子将产生如下输出: 1049: Unknown database 'nonexistentdb'
    1146: Table 'kossu.nonexistenttable' doesn't exist