How to show SQL error in PHP custom mysqli function?
I found a custom PHP function for mysqli query functions, but my problem is how can I show the error of the mysqli function?
Here is an example php mysqli function:
function connect()
{
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
$db = mysqli_select_db($con, DB_NAME);
return $con;
}
Request function:
function query($sql)
{
return mysqli_query(connect(),$sql);
}
Sampling function:
function fetchAssoc($sql)
{
return mysqli_fetch_assoc($sql);
}
And this 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 if the query fails, such as the wrong field name or the table does not exist?
source to share
After any query, the last mysqli error persists in reconnecting. To get it:
echo mysqli_error($con);
If you want to kill the script directly after the request if there is an error:
mysqli_query($con, "some query") or die(mysqli_error($con));
There is also an error number if you have a 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"'
source to share
I am using both 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 all your requests calling connect () function.
This way, if the server uses the query () function, your mysql connection will be 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;
}
source to share