如何在PHP中的mysql查询中获取有用的错误消息?



(1)

在else-block中,您可以看到,如何捕获MySQL错误并在警报中显示它们。

if(isset($_POST['btnSubmit'])) {
    $name = mysqli_real_escape_string($conn,$_POST["name"]);
    $sql = "INSERT INTO isodetail(title) VALUES ('{$name}')";
    $run = mysqli_query($conn, $sql);

    if($run) {
        echo "<script>alert('Certi Added Successfully');window.open('isocerti.php','_self');</script>";
    } else {
        $error = addslashes(mysqli_error($conn));
        echo "<script>alert('An Error occur: {$error}');</script>";
    }
}

参考文献:MySQLi-Error: php.net/manual/en/mysqli.error.php ://php.net/manual/en/mysqli.error.php
逃避特殊字符: http://php.net/manual/en/function.addslashes.phphttp://php.net/manual/en/function.addslashes.php (它完成了这个例子的工作)

HTML代码

<form class="col s6 " method="post" enctype="multipart/form-data">
   <div class="input-field col s12">
      <input id="last_name" type="text" name="name" class="validate">
      <label for="last_name">Certificate Name</label>
   </div>
   <button type="submit" id="btnSubmit" name="btnSubmit" class="btn btn-default" style="margin-top:20px;">ADD</button>
</form>

PHP代码

<?php
 include('footer.php'); 

include('conn.php');
if(isset($_POST['btnSubmit']))
{
    $name = mysqli_real_escape_string($conn,$_POST["name"]);

    $sql = "INSERT INTO `isodetail`(`title`) VALUES ('$name')";

    $run = mysqli_query($conn, $sql);

    if($run)
    {
        echo "<script>alert('Certi Added Successfully')</script>";
        echo "<script>window.open('isocerti.php','_self')</script>";
    }
    else
    {
        echo "<script>alert('Something Error!..please try Again..')</script>";
    }
}

 ?>

这显示一条警告消息,说出 Something Error!..please try Again.. 所以 mysqli_query 有错吗?





php