RajkumarLA
RajkumarLA

Reputation: 13

how to validate form in php?

how to validate this form. when user submits without selecting the options, he must get an alert.

my code:

echo "<form method='post' id='submit' action='checkresult.php'>";
$sql="SELECT * FROM cquestions where showdate='$today' limit 2";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<p>" . $row['cqtext'] . "</p>";
$sql2="SELECT * FROM canswers where cqid=".$row['cqid'];
$result2=mysql_query($sql2);
while($row2=mysql_fetch_assoc($result2))
{
echo "<input type='radio' name='".$row['cqid']."' value='".$row2['cqans']."' />".$row2['aatext']; }
}

Upvotes: 0

Views: 227

Answers (2)

The method you used is correct but syntax is wrong:

<?php
$marks+=$_POST['$cqid']; //Not Correct!
//1st You haven't defined $cqid. Its $qid.
//2nd You can't use a variable inside single quotes.
//PHP will consider it as normal String. But you can use it inside double quotes.
//But remember you can't use array ($row['cqid']) inside double quotes.
?>


This is the correct method:

<?php
while ($row = mysql_fetch_array($result)) {
    //$qid=$row['cqid'];
    //$marks+=$_POST[$qid]; //Correct!
    //But, Not needed You can directly use $row['cqid'] as an index.
    $marks+=$_POST[$row['cqid']];
}
?>


Update: [For debugging]

while ($row = mysql_fetch_array($result)) {
    $marks+=$_POST[$row['cqid']];
    echo $marks.'<br/>';
}
$insert="insert into result(email,marks)values('$email',$marks)";
$insert = mysql_query($insert);
if(!$result) {
    die('Unable to perform insert action. The following error occured: '.  mysql_error());
} else {
   echo 'The following Query: <b>'.$insert.'</b> executed successfully!';
}

Also Check the value of $email I can't see from where you are getting that value from.

And $login_session = $_POST['email']; This line is repeated twice but I am sure this value is always empty, because in test.php you have commented the following line:

echo "<input type='hidden' name='email' value='email' />";

The value attribute: value='email' obviously seems to wrong!

Check all these things, I guess You can carry-on from here now... :) If not, I am still glad to help you...

Update: [For setting limit in query]

SELECT * FROM `cquestions` LIMIT 0,3;
//Will fetch first three records from cquestions.
SELECT * FROM `cquestions` LIMIT 2,3;
//Will fetch 3rd, 4th and 5th records from cquestions.

Upvotes: 0

Midnightly Coder
Midnightly Coder

Reputation: 1053

What you are looking for are $_POST Variables. When you submit a form that uses action='checkresult.php', then on the checkresult.php you will be able to use the $_POST command to retrieve the variable values.

test.php page (using what the form outputs):

<form method='post' id='submit' action='checkresult.php'>
<input type='radio' name='the_name' value='the_value' />
<input type="submit">
</form>

checkresult.php:

echo $_POST["the_name"];
// Output = the_value

Upvotes: 1

Related Questions