如何在PHP自定义mysqli函数中显示SQL错误? [英] How to show SQL error in PHP custom mysqli function?

查看:134
本文介绍了如何在PHP自定义mysqli函数中显示SQL错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个用于mysqli查询函数的PHP自定义函数,但是我的问题是,如何显示mysqli函数的错误?

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?

这是示例php mysqli函数:

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;
}

查询功能:

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

获取关联函数:

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'];

如果SQL查询正确或不存在错误的字段名称或表之类的查询错误,如何在此处显示?

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

推荐答案

任何查询后,最后一个mysqli错误存储在连接资源中.要检索它:

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);

示例:

mysqli_select_db($con, "something") or die(mysqli_error($con));
//if the database is not found it'd print out 'Unknown database "something"'

这篇关于如何在PHP自定义mysqli函数中显示SQL错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆