-5

How can MySql database errors like 'trying to insert duplicate record' be captured and displayed in PHP?

get this error when inserting -- Warning: mysqli_error() expects parameter 1 to be mysqli, boolean.

In this case i know I'm getting it because I'm trying to insert a duplicate record. does php/mysql not give specific errors? which i could display on screen for end user to understand .

function querydb($sql){

        $con=mysqli_connect("localhost","my_user","my_password","my_db");

            // Check connection
            if (mysqli_connect_errno()) {
              echo "Failed to connect to  Database: " . mysqli_connect_error();
              return 0;
            }

            $result = mysqli_query($con,$sql)  or die("Error in the query.." . mysqli_error($result));
            $con->close();

            return $result;
}
PHPuser
  • 1
  • 1
  • 1
    Provide more information on how you access the DB. Are you using PDO, MySQLi ? – pbaldauf Dec 05 '14 at 19:21
  • This?: http://php.net/manual/en/mysqli.error.php – David Dec 05 '14 at 19:24
  • 1
    Googeling your thread title leads me [here](http://php.net/manual/en/mysqli.error.php). If this does not help you, be more specific, – Rangad Dec 05 '14 at 19:25
  • @Saifur $sql = "delete from student where Sid='$Sid';"; function querydb($sql){ $con=mysqli_connect("localhost","my_user","my_password","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to Database: " . mysqli_connect_error(); return 0; } $result = mysqli_query($con,$sql) or die("Error in the query.." . mysqli_error($result)); $con->close(); return $result; } – PHPuser Dec 05 '14 at 19:28
  • Echo your $sql, maybe $Sid is returning null. – Dimas Pante Dec 05 '14 at 19:30
  • @Dimas Pante done that. Its not null. – PHPuser Dec 05 '14 at 19:32
  • You're simply looking for `mysqli_error($con)` and `if ($result)`. Also scrape your whole `querydb` function; as it obviously deters from utilizing parameter binding. Preferrably read up on PDO instead. – mario Dec 05 '14 at 19:34

1 Answers1

0

First turn on the error reporting. Add on top of your file:

error_reporting(E_ALL);

Then if the log doesn't make sense to you, try writing the SQL and pasting it into phpMyAdmin, it'll probably show a different error (if it's being caused by sql).

Dimas Pante
  • 2,466
  • 22
  • 30