For Loop +错误记录已插入

时间:2011-07-28 12:27:50

标签: php mysql sql-update

您好,我有一个包含subj_ids的表单。所以这是场景。我有subj_ids 1,2,3,4,6但是每次我提交表单时会发生什么,它会插入一个带有0值的记录加上它不会插入一个subj_id为6的记录。

表格:

    <tr>
        <td width="225"><?= $row_subjects[1];?>
        <?php if($row_active_term[0] == '1st' && $row_active_term[1] == '1' ) {?>
        <td align="center"  width="225">
            <?php if($row_subjects['indicator'] == 'editable'){?>
                <input type="hidden" name="subj_id_<?= $row_subjects[0]?>" id="subj_id_<?= $row_subjects[0]?>" value="<?= $row_subjects[0]?>" />
                <input type="text" name="grade_<?= $row_subjects[0]?>" id="grade_<?= $row_subjects[0]?>" size="5" value="<?= number_format($row_subjects[4], 1)?>" />
            <?php } else {?>
                <a href="#" title="This is your downfall">?</a>
            <?php } ?>
        </td>
        <?php } ?>
    </tr>

提交: 我猜这是坏代码的所在。 。 。

    <?php
include('conn.php');
$uid = $_SESSION['uid'];
$rs_count_subjs = mysql_query("select count(*) as x from teachers_subjects where tid = $uid");
$row_count_subjs = mysql_fetch_array($rs_count_subjs);
$x = $row_count_subjs['x'];
$term = $_POST['term'];
//echo "select count(*) as x from teachers_subjects where tid = $uid";

$rs_subjs = mysql_query("select * from teachers_subjects where tid = $uid");
$row_subjs = mysql_fetch_array($rs_count_subjs);

for($i=0; $i<=$x; $i++) {
$t = $row_subjs[0];
$sid = $_POST['sid'];
$s = $_POST['subj_id_'.$i];
$y = $_POST['grade_'.$i];
$rs = mysql_query("select * from student_friggin_grades where sid = '$sid' AND subj_id = '$s' AND term = '$term' AND tid = $uid");
$row = mysql_fetch_array($rs);
$num = mysql_num_rows($rs);
    if($num > 0) {
        $update_grade = "update set grade = '$y' where sid = '$sid' AND subj_id = '$s' AND term = '$term' AND tid = $uid";
        $updated_grade = mysql_query($update_grade);
        $is_updated = mysql_affected_rows();
        echo "update set grade = '$y' where sid = '$sid' AND subj_id = '$s' AND term = '$term' AND tid = $uid";
    } else {
        $update_grade = "insert into student_friggin_grades(`sid`, `subj_id`, `term`, `grade`, `tid`, `date_added`, `date_updated`) 
                values('$sid', '$s', '$term', '$y', $uid, NOW(), NOW())";
        $updated_grade = mysql_query($update_grade);
        $is_updated = mysql_affected_rows();
    }
}

if($is_updated > 0) {
    header("Location: show_grades.php?sid=$sid");
}
?>

请帮助我,

XXXXXXXXXXXXXXXX

2 个答案:

答案 0 :(得分:1)

假设$ x等于6,

for($i=0; $i<=$x; $i++) {

会给你0到6 如果你想要遍历1到6

for($i=1; $i <= $x; $i++) {

然而,这并没有回答为什么你没有看到6,除非$ x实际上等于5。

答案 1 :(得分:1)

一个基于零和基于零? 我认为你有一个循环,它在最后一条记录之前终止了吗?