提问人:JeanneMeoy 提问时间:9/2/2022 最后编辑:JeanneMeoy 更新时间:9/2/2022 访问量:42
如何不显示 SQL 准备语句错误 [重复]
How to not show SQL prepare statement errors [duplicate]
问:
我有一个表单,用于向用户添加新的监视。为此,我将 prepare 语句与 mysqli 一起使用。
mysqli 代码:
function addMonitoring( mysqli $db, string $date, int $time, int $num_user, int $num_action, string $remark ): int
{
if(
$stmt = $db->prepare( 'INSERT INTO monitoring (
`date`,
`time`,
`num_user`,
`num_action`,
`remark`
)
VALUES ( ?, ?, ?, ?, ? )
')
) {
$stmt->bind_param( 'siiis', $date, $time, $num_user, $num_action, $remark );
$stmt->execute();
$stmt->close();
if(
$stmt = $db->prepare( 'SELECT m.id FROM monitoring m ORDER BY m.id DESC LIMIT 1')
)
{
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $id );
if( $stmt->fetch() ) {
return $id;
}
$stmt->close();
}
}
return 0;
}
我尝试显示测试错误,所以我在我的$time变量中放置了一个字符串类型,我想知道如何不显示此处看到的错误消息:
出现类似“发生错误”的消息
视图中用于添加监视的代码
if( isset( $_POST['add'] ) ) {
// dd($_POST);
addMonitoring( $db, $_POST['date'], $_POST['time'], $_POST['num_user'], $_POST['action'], $_POST['remark'] );
redirect( '/user/?num_user='.$_POST['num_user'] );
}
例如,如果我不使用准备好的语句,我这样做:
$query = "INSERT INTO monitoring (
`date`,
`time`,
`num_user`,
`num_action`,
`remark`
)
VALUES ( $date, $time, $num_user, $num_action, $remark )"
$result = mysqli_query( $db, $query );
$query = "SELECT m.id FROM monitoring m ORDER BY m.id DESC LIMIT 1";
$result = mysqli_query( $db, $query );
return ( !( $result === false ) && ( $row = mysqli_fetch_row( $result ) ) )?$row[0]:0;
如果mysql遇到问题,我可以返回int或0,因此如果我有“0”,我可以显示自定义消息
答:
-1赞
prashant
9/2/2022
#1
可以使用异常处理来实现它。
如果要向用户显示可读的错误消息,则可以尝试对代码进行以下更改。
function addMonitoring( mysqli $db, string $date, int $time, int $num_user, int $num_action, string $remark ): int
{
try {
if(
$stmt = $db->prepare( 'INSERT INTO monitoring (
`date`,
`time`,
`num_user`,
`num_action`,
`remark`
)
VALUES ( ?, ?, ?, ?, ? )
')
) {
$stmt->bind_param( 'siiis', $date, $time, $num_user, $num_action, $remark );
$stmt->execute();
$stmt->close();
if(
$stmt = $db->prepare( 'SELECT m.id FROM monitoring m ORDER BY m.id DESC LIMIT 1')
) {
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $id );
if( $stmt->fetch() ) {
return $id;
}
$stmt->close();
}
}
} catch (Exception $e) {
// If you don't want to handle exception then keep it empty.
// But its better to handle exception
echo $e->getMessage();
}
return 0;
}
评论
0赞
JeanneMeoy
9/2/2022
它不起作用,我仍然有一个带有sql错误的空白页,我编辑了我的代码以在添加监视的视图上显示代码
0赞
Dharman
9/3/2022
这是一个相当无用的建议。PHP 将显示错误消息或正确记录它,而无需 try-catch。无论哪种方式,如果语句都不是必需的。
评论
if (!ctype_digit($time)) echo "Time must be numeric"