douyan1896 2015-07-31 03:13
浏览 116
已采纳

如何在PHP自定义mysqli函数中显示SQL错误?

I have found a PHP custom function for mysqli query functions, but my problem is, how can I show an error of the mysqli function?

Here is the sample php mysqli function:

function connect()
{
    $con    =   mysqli_connect(DB_HOST, DB_USER, DB_PASS);
    $db     =   mysqli_select_db($con, DB_NAME);
    return $con;
}

Query Function:

function query($sql)
{
    return mysqli_query(connect(),$sql);
}

Fetch Assoc Function:

function fetchAssoc($sql)
{
    return mysqli_fetch_assoc($sql);
}

And here is how it was called or used:

$sql_select = query("SELECT * FROM table_name");
$sql_result = fetchAssoc($sql_select);
$tbl_id = $sql_result['id'];

How can I show here if the SQL query is correct or have query error like incorrect field name or table does not exist?

  • 写回答

3条回答 默认 最新

  • douren2831 2015-07-31 03:24
    关注

    After any query the last mysqli error is stored in the connection resourece. To retrieve it:

    echo mysqli_error($con);
    

    If you want to kill the script directly after the query if there is an error:

    mysqli_query($con, "some query") or die(mysqli_error($con));
    

    There is also error number if you ever have the need:

    echo mysqli_errno($con);
    

    Example:

    mysqli_select_db($con, "something") or die(mysqli_error($con));
    //if the database is not found it'd print out 'Unknown database "something"'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?