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 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建