Q:

MySQL code only gets executed once rather than multiple times in a loop

<?PHP
session_start();
if (isset($_SESSION['hasVoted']) && $_SESSION['hasVoted'] == '1') {
        print "You've already voted";
    }
else {
    if (isset($_POST['Submit1'])) {
        $ID = $_SESSION['user']; // obtain the ID of the user from the login session
        var_dump($ID);
        $string_results = $_POST['h2'];
        $selected_radio = explode(',', $string_results);
        var_dump($selected_radio);
        $user_name = "root";
        $password = "";
        $database = "surveyTest";
        $server = "127.0.0.1";
        $SQL = "SELECT * FROM tblquestions";
        $db_handle = mysql_connect($server, $user_name, $password);
        $db_found = mysql_select_db($database, $db_handle);
        if ($db_found) {
            $result = mysql_query($SQL);
            $numRows = mysql_num_rows($result); //return number of rows in the table
            var_dump($numRows);
            $qNum = 'q1';
            for ($i = 0; $i < $numRows; $i++)
            {
                var_dump($qNum);
                $_SESSION['hasVoted'] = '1';
                $selected_Value = $selected_radio[$i];
                var_dump($selected_Value);
            //==================================================================================
            //  SET Multiple rows IN THE answers TABLE for each question for a given student.
            //==================================================================================
                $SQL = "INSERT INTO answers (QID, Answer, SID) VALUES ('$qNum', '$selected_Value', '$ID')";
                $result = mysql_query($SQL);
                    $question_Number = ltrim($qNum,'q');
                    $question_Number++;
                    $qNum ='q'.$question_Number;
            }
                mysql_close($db_handle);
                print "Thank you for participating!";
        }
        else {
        print "database error";
        }
    }

    else {
        header("location:login.php");;
    }
}
session_destroy();
?>

<html>
<head>
<title>Process Survey</title>
</head>

<body>

</body>
</html>

When I execute the above code, the $SQL statement that consists of the INSERT only gets executed once. This means that it is only adding a single record to the database. However, I need it to add several records to the database which is equal to $numRows. The print out of $qNum and $selected_Value show the right thing. Any suggestions?

A:

try again using $result = mysql_query($SQL) or die(mysql_error());
also are the Primary keys ok on your table?

