doulu1945
doulu1945
2015-06-23 09:19

php foreach循环插入数据反馈每次重复

已采纳

this is my php code. hire is a problem i use check box selection and insert data in my database. but it insert data by foreach loop. so when press ok if data successfully insert then for 3 selection it say

successfully register successfully register successfully register but i want it say only once successfully register

<?php 

    $db=require "script_database/connect.php";  
    $query = "SELECT * FROM course";
    $query1="select * from selection where student_id='1229CSE00241' and semester='FALL2015' ";
    $key=mysql_query($query1);


            if(mysql_num_rows($key)>0)
            {
            echo "you already selected courses for registration";
            }

    else if($_POST['buy']==''){
    echo "<h2><center>You didn't select any courses</h2></center>";
    }

    else{
    foreach($_POST['buy'] as $item) {

    $query = "SELECT * FROM course WHERE id = $item
    ";

    if ($r = mysql_query($query)) { 

        while ($row = mysql_fetch_array($r)) {

        $student_id="1229CSE00241";
        $id=$item;
        $course_id=$row['course_id'];
        $course_title=$row['course_title'];
        $course_credits=$row['course_credits'];
        $course_status=$row['course_status'];
         $semester="FALL2015";
        }


    } else { 
        print '<p style="color: blue">Error!</p>';
    } 

    {


    $insert_query="insert into selection(student_id,semester,course_id,course_title,course_credits,course_status,date_time) values ('$student_id','$semester','$course_id','$course_title','$course_credits','$course_status',NOW())";
    }

    //here is my problem 
    //it repeat every time when insert data but i want to make it only once

    if(mysql_query($insert_query))
    {
    echo "successfully register";
    }
    else 
    echo "problem show";


    }

    }?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duangewu5234 duangewu5234 6年前

    Before you start your foreach loop set a flag like:

     $error = false;
    

    Then in your loop

    if(!mysql_query($insert_query))
    {
        $error =true;
    }
    

    And after the loop has closed

    if($error){
       echo "problem show";
    }else{
       echo "successfully register";
    }
    
    点赞 评论 复制链接分享