doulu1945 2015-06-23 01:19
浏览 366
已采纳

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 2015-06-23 01:22
    关注

    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";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部