3

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?

0

3 Answers 3

2

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"'
Sign up to request clarification or add additional context in comments.

1 Comment

Depends how you need to use it. Or how you want to read it. Is it just for debugging? The error is stored after any mysqli query. So you can call the error function after any query. It stores the last error. After mysqli_query or after mysqli_select_db to see if there was an error getting the db. Any mysqli error can be retrieved that way
0

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

2 Comments

mysql is outdated and less secure. You need to use mysqli lol.
thanks for advising. Bu all my libraries are designed for mysql.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.