我在 PHP 表中插入了已经检查过的值,但是当我选择多个项目时,我会收到多条成功或失败消息。
这是我插入数据库的代码。
//insert.php
include_once 'includes/dbconnect.php';
if(!empty($_POST['perms']))
{
$output = '';
$perms = $_POST['perms'];
$role = mysqli_real_escape_string($conn,$_POST['role']);
$module = mysqli_real_escape_string($conn,$_POST['module']);
foreach ($perms as $perm) {
$query = "INSERT INTO roles_permissions (role_id,module_id,perm_id)
VALUES ('$role','$module','$perm')";
if(mysqli_query($conn, $query))
{
$output .= '
<script>
bootbox.alert("<h4>Success:</h4> <p>Permissions have been added to selected role successfully </p>",function(){
window.location.reload(); });
</script>';
} else {
$output .= '
<script>
bootbox.alert("<h4>Sorry!</h4><p>Operation was not successful, Please cross check and try again.</p> ",function(){ window.location.reload(); });
</script>';
}
}
echo $output;
}
?>
提前感谢您的帮助
答案1
您会收到多条成功消息,因为构建消息的代码位于您的 foreach 循环内。如果您只想要一条消息,则必须将其移出循环。
<?php
//insert.php
include_once 'includes/dbconnect.php';
if(!empty($_POST['perms'])) {
$output = '';
$perms = $_POST['perms'];
$role = mysqli_real_escape_string($conn,$_POST['role']);
$module = mysqli_real_escape_string($conn,$_POST['module']);
foreach ($perms as $perm) {
$query = "INSERT INTO roles_permissions (role_id,module_id,perm_id)
VALUES ('$role','$module','$perm')";
$result = mysqli_query($conn, $query);
// if we get an error stop the loop
if ( ! $result) { break; }
}
if ($result) {
$output = '<script>
bootbox.alert("<h4>Success:</h4> <p>Permissions have been added to selected role successfully </p>",function(){
window.location.reload(); });
</script>';
} else {
$output = '<script>
bootbox.alert("<h4>Sorry!</h4><p>Operation was not successful, Please cross check and try again.</p> ",function(){ window.location.reload(); });
</script>';
}
echo $output;
}
?>
你的脚本也可以SQL 注入攻击。 甚至如果您正在逃避输入,那就不安全了! 你应该考虑使用准备好的参数化语句在
MYSQLI_
或PDO
API 中,而不是连接值
使用准备好的语句还具有潜在的速度优势,因为您可以准备查询语句(准备基本上意味着编译和优化)并在更改参数值后多次重复使用它
所以你的代码看起来像这样
<?php
//insert.php
include_once 'includes/dbconnect.php';
if(!empty($_POST['perms'])) {
$output = '';
$query = "INSERT INTO roles_permissions
(role_id,module_id,perm_id) VALUES (?,?,?)";
$stmt = $conn->prepare($query);
foreach ($perms as $perm) {
// for the purpose of this example I assumed all 3 values were integers
$stmt->bind_params('iii', $_POST['role'], $_POST['module'], $prem);
$result = $stmt->execute();
// if we get an error stop the loop
if ( ! $result) { break; }
}
if ($result) {
$output = '<script>
bootbox.alert("<h4>Success:</h4> <p>Permissions have been added to selected role successfully </p>",function(){
window.location.reload(); });
</script>';
} else {
$output = '<script>
bootbox.alert("<h4>Sorry!</h4><p>Operation was not successful, Please cross check and try again.</p> ",function(){ window.location.reload(); });
</script>';
}
echo $output;
}
?>