How to show SQL error in PHP custom mysqli functio

2020-07-22 19:05发布

问题:

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?

回答1:

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:

i use like in mysql_ not mysqli.

function query($sql, $flag= false){

 $result  = mysqli_query(connect(),$sql);

 if($flag == true && $result == false )
 {
     echo mysqli_errno()."_--".mysqli_error()."<br /> in query.:".$sql;
 }

  return $result;

}

another problem is your all queries calling connect() function .

so whenerver you use function query(), your mysql connection will reset.


$mysql_con;

$mysql_con = connect();

function query($sql, $flag= false){

 global $mysql_con;

 $result  = mysqli_query($mysql_con,$sql);

 if($flag == true && $result == false )
 {
     echo mysqli_errno()."_--".mysqli_error()."<br /> in query.:".$sql;
 }
  return $result;
}


回答3:

You can make use of php function mysqli_error() and mysqli_errno() you can visit php.net for detailed documentation on this functions