如何解决只获得最后一行更新的问题?

时间:2017-01-04 17:15:40

标签: php mysql

我试图将多行更新到数据库中,但每次只能更新第四行,即$ anstext4。可能是什么错误?

PHP代码:

<?php

$_POST = array(); //workaround for broken PHPstorm
parse_str(file_get_contents('php://input'), $_POST);

session_start();

if(isset($_SESSION['doctor'])) {

    require 'dbConn.php';

    $id = null;
    if(!empty($_GET['id'])) {
        $questionid = $_REQUEST['id'];
    }

    if(null==$questionid) {
        header("location: admin_home.php");
    }

    if(!empty($_POST)) {

        $questiontextError = null;
        $anstext1Error = null;
        $anstext2Error = null;
        $anstext3Error = null;
        $anstext4Error = null;

        $questiontext = $_POST['questiontext'];
        $anstext1 = $_POST['ans1'];
        $anstext2 = $_POST['ans2'];
        $anstext3 = $_POST['ans3'];
        $anstext4 = $_POST['ans4'];

      //$answers = $_POST['ans'];
        //$answers = array($_POST['ans1'], $_POST['ans2'], $_POST['ans3'], $_POST['ans4']);
        //$answers = array($_POST['ans']);

       /*$answers[] = $_POST['ans1'];
        $answers[] = $_POST['ans2'];
        $answers[] = $_POST['ans3'];
        $answers[] = $_POST['ans4'];*/

        $radiobtn = $_POST['radioans'];

        $valid = true;
        if(empty($questiontext)) {
            $questiontextError = 'Please enter valid data';
            $valid = false;
        }

       /* if(empty($anstext1)) {
            $anstext1Error = 'Enter the first data';
            $valid = false;
        }

        if(empty($anstext2)) {
            $anstext2Error = 'Enter the second data';
            $valid = false;
        }

        if(empty($anstext3)) {
            $anstext3Error = 'Enter the third data';
            $valid = false;
        }

        if(empty($anstext4)) {
            $anstext4Error = 'Enter the fourth data';
            $valid = false;
        }*/

        //Update the data
        if($valid) {

            $sql = "UPDATE `question` 
                        SET `question_text` = :questiontext,
                            `question_type` = 'mcq',
                            `correct_answer` = :radioans
                        WHERE question.id = ".$questionid;


            //$result = $conn->query($sql);
            $result = $conn->prepare($sql);
            $result->bindParam(":questiontext", $questiontext);
            $result->bindParam(":radioans", $radiobtn);
            //$result->execute(array($questiontext,$radiobtn));
            $result->execute();

           // $count= null;
            /*for($i=0; $i<$count; $i++) {
                $sql2 = "UPDATE `option_tbl` SET option_answer=':ans[$i]' WHERE question_id = ".$questionid;
                $result2 = $conn->prepare($sql2);

                $result2->execute();
            }*/

           /*$sql2 = "UPDATE `option_tbl`
                         SET `option_answer` = :ans
                         WHERE question_id = ".$questionid;

            $result2 = $conn->prepare($sql2);*/

           $sql2 = "UPDATE `option_tbl`
                            SET `option_answer` = :ans
                          WHERE question_id = '$questionid'";
           $result2 = $conn->prepare($sql2);

            $result2->bindParam(":ans",$anstext1);
            $result2->execute();
            $result2->bindParam(":ans",$anstext2);
            $result2->execute();
            $result2->bindParam(":ans",$anstext3);
            $result2->execute();
            $result2->bindParam(":ans",$anstext4);
            $result2->execute();

            //$result2->bindParam(":ans", $answers);
            $result2->execute();


           /*$result2->execute(array(":ans" => $_POST['ans1'],
                                    ":ans" => $_POST['ans2'],
                                    ":ans" => $_POST['ans3'],
                                    ":ans" => $_POST['ans4']));*/

           /*for($i=0; $i < count($questionid); $i++) {
               $result2->execute([
                                    ':ans' => $_POST['ans1'][$i],
                                    ':ans' => $_POST['ans2'][$i],
                                    ':ans' => $_POST['ans3'][$i],
                                    ':ans' => $_POST['ans4'][$i]]);
               print_r($result2);
           }*/


            /*foreach ($answers as $answer) {

               $result2 = $conn->prepare("UPDATE `option_tbl` SET `option_answer` =? WHERE question_id =?");
               $result2->bindParam("ss", $answer, $questionid);
               $result2->execute();

           }*/

            /*$sql2 = "UPDATE `option_tbl` SET `option_answer` = :ans WHERE '$questionid' = :id";

            foreach ($answers as $key => $answer) {
                $result2 = $conn->prepare($sql2);
                $result2->bindParam(':ans', $answer);
                //$result2->bindParam(':id', $questionid);
                $result2->execute();
            }*/

            $conn = null;

            //header('Location: '.$_SERVER['PHP_SELF']);
            echo "Successful";

        }
    }


?>

这两个答案都会影响整个列结果,使其成为最后一个值。

HTML code:

<!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" type="text/css" href="Assets/index_style.css"/>
        <link rel="stylesheet" href="bootstrap/css/bootstrap.css"/>
        <link href="https://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet">
        <script src="Assets/jquery-1.11.3-jquery.min.js"></script>

        <script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

        <script>
            //back button function
            function goBack() {
                window.history.back();
            }
        </script>


    </head>
    <body>

    <div class="container">
        <div class="header clearfix">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="settings.php">Settings</a></li>
                    <li role="presentation"><a href="logout.php">Logout</a></li>
                </ul>
            </nav>
        </div> <!-- /container -->

        <div class="container">
            <button type="button" class="btn btn-success" onclick="goBack()">back</button>
            <br>

            <h3 class="text-muted">Update the data</h3>

            <div class="span10 offset1">

                <form class="form-horizontal" action="admin_update.php?id=<?php echo $questionid?>" method="POST">


                    <div class="control-group <?php echo !empty($questiontextError)?'error':'';?>">
                        <label class="control-label">Question: </label>
                        <div class="controls">
                            <input name="questiontext" type="text" size="60" placeholder="Question" value="<?php echo !empty($questiontext)?$questiontext:'';?>">
                            <?php if (!empty($questiontextError)): ?>
                                <span class="help-inline"><?php echo $questiontextError;?></span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="control-group <?php echo !empty($anstext1Error)?'error':'';?>">
                        <label class="control-label">1.</label>
                        <!--<div class="controls">-->
                            <input name="ans1" type="text" size="40" value="<?php echo !empty($anstext1)?$anstext1:'';?>">
                            <input type="radio" name="radioans" value="1">
                            <?php if (!empty($anstext1Error)): ?>
                                <span class="help-inline"><?php echo $anstext1Error;?></span>
                            <?php endif;?>
                        <!--</div>-->
                    </div>

                    <div class="control-group <?php echo !empty($anstext2Error)?'error':'';?>">
                        <label class="control-label">2.</label>
                        <!--<div class="controls">-->
                        <input name="ans2" type="text" size="40" value="<?php echo !empty($anstext2)?$anstext2:'';?>">
                        <input type="radio" name="radioans" value="2">
                        <?php if (!empty($anstext2Error)): ?>
                            <span class="help-inline"><?php echo $anstext2Error;?></span>
                        <?php endif;?>
                        <!--</div>-->
                    </div>

                    <div class="control-group <?php echo !empty($anstext3Error)?'error':'';?>">
                        <label class="control-label">3.</label>
                        <!--<div class="controls">-->
                        <input name="ans3" type="text" size="40" value="<?php echo !empty($anstext3)?$anstext3:'';?>">
                        <input type="radio" name="radioans" value="3">
                        <?php if (!empty($anstext3Error)): ?>
                            <span class="help-inline"><?php echo $anstext3Error;?></span>
                        <?php endif;?>
                        <!--</div>-->
                    </div>

                    <div class="control-group <?php echo !empty($anstext4Error)?'error':'';?>">
                        <label class="control-label">4.</label>
                        <!--<div class="controls">-->
                        <input name="ans4" type="text" size="40" value="<?php echo !empty($anstext4)?$anstext4:'';?>">
                        <input type="radio" name="radioans" value="4">
                        <?php if (!empty($anstext4Error)): ?>
                            <span class="help-inline"><?php echo $anstext4Error;?></span>
                        <?php endif;?>
                        <!--</div>-->
                    </div>

                    <div class="form-actions">
                        <button type="submit" class="btn btn-success">Update</button>
                        <a class="btn" href="crud.php">Back</a>
                    </div>


                </form>

            </div>

        </div>


        <footer class="footer">
            <p>&copy; 2016, Inc.</p>
        </footer>

    </body>
    </html>
    <?php
    }
    ?>

我尝试过使用foreach但它不会工作

foreach ($answers as $answer) { 
    $stmt = $conn->prepare("UPDATE option_tbl SET option_answer = :ans  
                             WHERE question_id = '$questionid'"); 
    $stmt->execute(); 
}

2 个答案:

答案 0 :(得分:0)

使用每个绑定参数进行foreach循环更新。您要为一个参数设置4个值,这就是为什么它取最后一个参数的原因。你需要一个循环

试试这个:

if (!empty($_POST)) {
    $answers = array($_POST['ans1'], $_POST['ans2'], $_POST['ans3'], $_POST['ans4']);

    foreach ($answers as $answer) {
        $result = $conn->prepare("UPDATE option_tbl SET option_answer =? WHERE question_id =?");
        $result->bindParam("ss", $answer, $questionid);
        $result->execute();
    }
}

答案 1 :(得分:0)

首先,您需要知道要为每个查询进行seprade调用,因此您需要进行“准备”。呼唤evry电话 (有一种方法可以在一次通话中完成,但我们现在就把它留下来) 所以

if(!empty($_POST)){
    $answers = $_POST // duplicate _POST array into answers

    // Declering the sql template, pay attenion that I make another param to bind in, :id
    $sql = "UPDATE `option_tbl` SET `option_answer` = :ans WHERE question_id = :id";

   // Then for each on answers array
   foreach ($answers as $key => $answer) {
       // prepare
       $result = $conn->prepare($sql);
       // bind the params
       $result->bindParam(':ans', $answer);
       $result->bindParam(':id', $YourId); // Best want is to do array of ids and bind the $key of the foreach in it
       // Execute the query
       $result->execute();
   }
}