【问题标题】:How to prevent multiple returns inside for loop in php?如何防止在php中的for循环内多次返回?
【发布时间】:2021-09-28 18:01:45
【问题描述】:

我试图插入多个具有相同名称的文件,但“echo”返回多个反馈。例如:Success、Success.... 或多个空字段。你能帮忙插入数据并只返回成功或空字段吗?感谢您的帮助!

global $conn;
if (isset($_POST['languages']) && isset($_POST['knowledge'])) {
    for ($i = 0; $i <= 10; $i++) {
        $id = $_SESSION["id"];
        @$languages = $_POST['languages'][$i];
        @$knowledge = $_POST['knowledge'][$i];
        if (!empty($languages)) {
            $sql = $conn->prepare("INSERT INTO languages (userid, languages,kn_level) VALUES (?,?,?)");
            $sql->bindParam(1, $id);
            $sql->bindParam(2, $languages);
            $sql->bindParam(3, $knowledge);
            if ($sql->execute()) {
                echo "Success";
                //header("location:/settings");
            } 
        }else{
            echo "Empty Fields";
        }
    }
    
}





$(document).on('click', '#langIdButton', function(e) {
        var data = $("#langSkills").serializeArray();
        
        $.ajax({
            data: data,
            type: "post",
            url: 'settings/addlanguage',
            success: function(data) {
                if (data == "Success") {
                    $('#lang_response').html(data).show()

                } else {
                    $('#lang_response').html(data).show()
                }
            }
        });
    });

【问题讨论】:

  • 在循环内设置一个标志,并检查循环外的标志来决定回显什么。如果在循环内回显,每次迭代都会得到一个响应。
  • 所以您只想知道 all 查询是否成功?如果有些是空的而有些不是呢?然后它应该只插入正确的数据而不是其余的,还是根本不插入任何行?你想要什么反馈?当然,您想确切地知道哪些数据有问题,以及是否有多个错误数据。请具体说明您在每种情况下期望的输出,因为我认为您没有真正考虑过。
  • 而不是使用错误抑制@(总是V.v.Bad)正确地测试是否存在(参见isset()
  • 当然,如果您测试了count($_POST['languages']) == count($_POST['knowledge']),然后使用count($_POST['languages']) 而不是任意的10 迭代来控制您的循环。大多数问题都会消失。

标签: php sql ajax


【解决方案1】:

将您的代码重构为第一次测试,然后再插入,具体取决于有多少好的值。

//test if there is a id
if(empty($_SESSION["id"])){
   //echo some error message
   die;
   }

//get the length of languages, create a empty result array and fetch the id
$len    = count( $_POST['languages'] );
$result = Array();
$id     = $_SESSION["id"];

 //test if $_POST['languages']) has the same length as $_POST['knowledge']
if( $len === count( $_POST['knowledge'] )){
    // if they are test each value
   foreach( $_POST['languages'] as $key => $language ){
       // first test the language. If empty: skip
      if($language === ''){
        continue;  
        }
       // then test the corresponding knowledge. If empty: skip
      if($_POST['knowledge'][$key] === ''){
        continue;  
        }
       // if both good: add the values to result
      $result[]=[ $id, $language, $_POST['knowledge'][$key] ];
    }
  //if the are not, something went wrong
else{
  //echo some error
    die;
    }
 //count the good values
$isgood = count( $result );

经过测试,$isgood 有一个从0(全错)到$len(全好)的数字。然后,您可以选择在并非所有数据都正确时执行的操作:仅插入正确的数据,或不插入任何内容。

 // stop when not all good
if($isgood !== $len){
    echo "Empty Fields";
    die;
    }
 // ===== OR =======
 // if nothing good, stop, else insert only the good ones
if($isgood === 0){
    echo "Empty Fields";
    die;
    }

$sql = $conn->prepare("INSERT INTO languages (userid, languages,kn_level) VALUES (?,?,?)");
foreach($result as $values){
   $sql->bindParam(1, $values[0] );
   $sql->bindParam(2, $values[1] );
   $sql->bindParam(3, $values[2] );
   $sql->execute();
   }          
echo 'Succes';

【讨论】:

  • 米歇尔,这是完美的伙伴!非常感谢!
猜你喜欢
  • 2022-09-26
  • 2013-10-13
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 2018-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多