I want to use prepared statement to insert and update data in mysqli,
Below is my database class,
class database extends mysqli
{
...
# insert and update data
public function query_stmt($sql,$types = null,$params = null)
{
# create a prepared statement
$stmt = parent::prepare($sql);
if($stmt)
{
# bind parameters dynamically for markers
if($types&&$params)
{
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++)
{
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
$return = call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
# execute query
$result = $stmt->execute();
if($result) return 'success!';
else return 'failed!';
# close statement
$stmt->close();
}
else
{
return self::get_error();
}
}
# display error
public function get_error()
{
if($this->errno || $this->error)
{
return sprintf("Error (%d): %s",$this->errno,$this->error);
}
}
public function __destruct()
{
parent::close();
//echo "Destructor Called";
}
}
It works fine when I have a correct query like this,
$sql = "
INSERT root_countries_cities_towns (
tcc_names,
cny_numberic,
tcc_created
)VALUES(
?,
?,
NOW()
)";
$mysqli->query_stmt($sql, 'ss',array('UK','004'));
But I want it to return something when I have an incorrect query, such as,
$sql = "
INSERT root_countries_cities_townx (
tcc_names,
cny_numberic,
tcc_created
)VALUES(
?,
?,
NOW()
)";
the table of root_countries_cities_townx does not exist. So I want the the method of query_stmt to return this type of error message to my browser. But my method doesn’t! Why?
I have tried to test it to return some default words whether it is ok or not, but nothing at all comes out on my browser,
# execute query
$result = $stmt->execute();
if($result) return 'success!';
else return 'failed!';
What should I add or change in the code so that it can return a positive message when it is ok and returns negative message when it is not ok?
Thanks.
You’re returning the error messages, not echoing them. You’d either have to modify the DB class to use
echoinstead of return, or do