I'm trying to validate a form of a test. I get an error in answer.php Basically I want to validate that each question has been answered.
The form:
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' ORDER BY q_nr";
$result1=mysql_query($sql1);
echo "<form method='post' name='form1' action='answer.php'>";
while($row1 = mysql_fetch_array($result1))
{
$q_nr=$row1['q_nr'];
$q_type=$row1['q_type'];
$question=$row1['question'];
$option1=$row1['option1'];
$option2=$row1['option2'];
$option3=$row1['option3'];
echo "<P><strong>$q_nr $question</strong><BR>";
echo "<BR>";
echo "</p>";
if ($q_type != 'mr') {
if($option1!="") {
echo "<input type='radio' name='question[$q_nr]' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='radio' name='question[$q_nr]' value='B'>$option2<BR>";
} else {
echo ''; }
if($option3!="") {
echo "<input type='radio' name='question[$q_nr]' value='C'>$option3<BR>";
} else {
echo ''; }
} else { // else if not <> mr
if($option1!="") {
echo "<input type='checkbox' name='question[$q_nr][]' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='checkbox' name='question[$q_nr][]' value='B'>$option2<BR>";
} else {
echo ''; }
if($option3!="") {
echo "<input type='checkbox' name='question[$q_nr][]' value='C'>$option3<BR>";
} else {
echo ''; }
} //end else if q_type <> mr
echo "<BR>";
echo "</p>";
} //end while row1
echo "<input type='submit' value='Submit' name='Submit'>";
echo "</form>";
answer.php
foreach($_POST['question'] as $key => $ans) {
if ($ans[] = '') {
echo "answer is empty";
}
}
I get the error: Warning: Invalid argument supplied for foreach() in ......
One thing is that you are assigning the answer rather than checking it, use ==
foreach($_POST as $key => $ans) {
if ($ans == '') {
echo "answer is empty";
}
}
and instead of using
name='question[$q_nr]'
I would use for the radio fields
name='question_{$q_nr}'
and for the checkboxes
name='question_{$q_nr}[]'
On answer.php you should be able to do a print_r($_POST) to check what you are getting.
This is probably because your $_POST['question'] is empty. This is what happens when you try to do this with an empty array.
Whereas your HTML says: name='question[$q_nr]'.
Print the values in the array to see what it contains, use print_r.
Edit: $_POST['question'] IS NOT an array! While $_POST IS an array...
Maybe you should try to do something like this:
foreach ($_POST as $key => $value)
Or do it however you want the result to be displayed.
Related
Data insertion is not happening when user is entering through a form.i am trying to ask user for firstname , lastname and phone number through 3 fields checking pattern side by side but data is not being inserted in db.
The code is as ->
main page i.e. allinfo.php:
<html>
<head></head>
<body>
<?php
$labels=array("firstname"=>"FirstName" , "lastname"=>"LastName" ,"phone"=>"PhoneNumber");
?>
<form action='blank.php' method='POST'>
<?php
foreach ($labels as $field => $value)
{
echo "<label for='$field'>$value</label>";
echo "<input type='text' name='$field'>";
}
echo "<input type='submit' value='Submit'>";
?>
</form>
</body>
Other page:
<html>
<head></head>
<body>
<?php
/*foreach($_POST as $field=>$value)
{
echo "$field = $value<br />";
}*/
/*foreach($_POST as $field)
{
echo "$field <br />";
}*/
$labels=array("firstname"=>"FirstName" , "lastname"=>"LastName" ,"phone"=>"PhoneNumber");
foreach ($_POST as $field => $name)
{
if($field!='lastname')
{
if(empty($name))
{
$blank_array[]=$field;
}
}
elseif($field=="phone")
{
if(!preg_match("/^ [0-9 ) ( -] {7-20} $/" , $name))
{
$bad_array[]=$field;
}
}
}
if(#sizeof($blank_array) > 0 or #sizeof($bad_array) > 0)
{
if(#sizeof($blank_array) > 0)
{
echo "<p>You have missed some of the values</p>";
foreach($blank_array as $name)
{
echo "{$labels[$name]}<br />";
}
}
if(#sizeof($bad_array) > 0)
{
echo "Please enter in correct format";
foreach($bad_array as $name)
{
echo "{$labels[$name]}";
}
}
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>"; /* re-display the form*/
foreach($labels as $field=>$name)
{
$good_data[$field]=strip_tags(trim($_POST[$field]));
echo "<label for='$field'>$name</label>";
echo "<input type='text' name='$field' value='{$good_data[$field]}'>";
}
echo "<input type='submit' value='Submit'>";
echo "</form>";
}
else
{
$host="localhost";
$acc="root";
$password="*******";
$database="member";
$cxn=mysqli_connect($host,$acc,$password,$database) or die("can not found");
foreach($labels as $field=> $name)
{
$good_data[$field]=strip_tags(trim($_POST[$field]));
if($field=="phone")
{
$good_data[$field]=preg_replace("/ [) ( . -] / " , " " , $good_data[$field]);
}
$good_data[$field]=mysqli_real_escape_string($cxn,$good_data[$field]);
}
$query="insert into user (";
foreach($good_data as $field =>$name)
{
$query.="$field";
}
$query.=") VALUES (";
$query=preg_replace("/,\)/",")",$query) ;
foreach($good_data as $field =>$name)
{
$query.="'$name',";
}
$query.=")";
$query=preg_replace("/,\)/",")",$query) ;
$result=mysqli_query($cxn,$query);
echo "new entry";
}
echo "<p>All the information is available ♥ </p>" ;
?>
</body>
Please help.
Change the loop where you build the query string
foreach($good_data as $field =>$name)
{
$query.="$field";
}
To
foreach($good_data as $field =>$name)
{
$query.="$field,";
}
Notice you missed the coma.
I have a table that has different names of competences and another one in which we have the competence_ID and the user_ID that has that competence. I have a form in which I submit the competences that apply to a certain user. Now, I want to retrieve these competences and check boxes in case they are valid.
I use this code, but it does not seem to work.
<?php
include "db.php";
$employees=mysql_query("SELECT * FROM asiakas");
echo "<form method='post' action='' id='employeesselection'><select name='select_employee' id='select_employee'>";
while($row=mysql_fetch_array($employees)){
$selected = ($row['Id'] == $_POST['select_employee'])?'selected="selected"':'';
echo '<option '.$selected.' value="'.$row['Id'].'">'.$row['Etunimi'].' - '. $row['Sukunimi'].'</option>';
}
echo "</select><input type='hidden' name='action' value='selectedemployee'>
<input type='submit' value ='submit' name='submit'><br/>";
if(isset($_POST['select_employee'])){
$specific=mysql_query("SELECT Id, Sukunimi,Etunimi from asiakas WHERE Id=".$_POST['select_employee']);
$sp=mysql_fetch_array($specific);
}
if(isset($sp['Etunimi']) && isset($sp['Sukunimi'])){
$comp=mysql_query("SELECT * FROM Competences");
echo "<br/>select competences for: ". $sp['Etunimi'];
$id= $sp['Id'];
$result=mysql_query("SELECT distinct c_ID from User_Competence WHERE e_ID=".$id);
while($test=mysql_fetch_array($result))
{
echo $test['c_ID'];
}
echo "<table><th>valid?</th><th>Competence description</th>";
$counter=0;
$traverse=0;
while($compi=mysql_fetch_array($comp)){
$checked='';
if($test[$traverse]==$counter){
$checked="checked";
$traverse++;
}
$counter ++;
echo "<tr><td><input type='checkbox'" .$checked." name='c[]' value='".$compi['Competence_ID']."'></td><td>".$compi['Competence_Description']."</td></tr>";
}
echo "</table>";
echo "<input type='hidden' name='action' value='selectchecked'>";
echo "<input type='submit' value='submit checks'>";
}
if(isset($_POST) && !empty($_POST)){
print_r($_POST);
}
if(isset($_POST['action']) && $_POST['action']='selectchecked'){
if (isset($_POST['c'])){
$s = $_POST['c'];
foreach ($s as $k => $v) {
if (is_array($v)) {
// array_push($s, implode('', array($v [$what])));
}
};
echo $abc= implode(',', $s);
for ( $a=0;$a<count($s);$a++){
$ar=explode(',',$abc);
echo $var= $ar[$a];
$q=mysql_query("INSERT INTO user_competence(c_ID, e_ID) VALUES ('".$var."','".$id."')");
}
}
}
echo "</form>";
?>
If you put checked as an attribute on the <input type="checkbox"> it will be checked, even if you leave the actual value of the attribute empty.
So change the following parts from...
$checked="checked";
...
echo "<tr><td><input type='checkbox' checked='".$checked."' name='c[]' ...
Into...
$checked="checked='checked'";
...
echo "<tr><td><input type='checkbox' ".$checked." name='c[]' ...
Which will mean if the $test[$traverse$] is true, checked='checked' will be placed into the HTML, otherwise it will be left out.
I have been using variable in the name part of the input tag. Now while access answers as selected by users using $_post,It gives error as undefined index.Tell me how to get answers of all questions as selected .
echo "<form method=\"post\" action=\"\">";
$query=mysql_query("select q_detail,q_id from question where category=\"$value2\"",$connection);
if(!$query)
{
echo mysql_error().'query failed';
}
$ans=1;
while($value1=mysql_fetch_array($query))
{
echo "Q-$i"." ";
echo $value1['q_detail']."<br />";
$i++;
$qno=$value1['q_id'];
$query1=mysql_query("select * from answer where ans_id=$qno");
if(!$query1)
{
echo mysql_error().'query failed';
}
while($value2=mysql_fetch_array($query1))
{
$opt=$value2['option1'];
$opt1=$value2['option2'];
$opt2=$value2['option3'];
$opt3=$value2['correct'];
echo "<input type=\"radio\" value=\"$opt\" name=\"$ans\">";
echo "<span class=\"margin\">$opt</span>";
echo "<input type=\"radio\" value=\"$opt1\" name=\"$ans\">";
echo $opt1." ";
echo "<input type=\"radio\" value=\"$opt2\" name=\"$ans\">";
echo $opt2." ";
echo "<input type=\"radio\" value=\"$opt3\" name=\"$ans\">";
echo $opt3." <br /><br />";
$ans++;
}
}
echo"<input type=\"submit\" name=\"submit\" value=\"submit\">";
echo "</form>";
You can make the name of input as array, e.g.:
<input type="radio" value="Blah" name="answers[]" />
and in php code you can access this using the following code:
foreach($_POST['answers[]'] as $answer)
{
echo $answer;
}
Enclose the non-numeric value with single quotes.
$query=mysql_query("select q_detail,q_id
from question where category='$value2'");
Try this:
$ans=1;
if(isset($_POST))
{
echo $_POST['radio_' . $ans];
}
echo "<form method=\"post\" action=\"\">";
$query=mysql_query("select q_detail,q_id from question where category=\"$value2\"",$connection);
if(!$query)
{
echo mysql_error().'query failed';
}
while($value1=mysql_fetch_array($query))
{
echo "Q-$i"." ";
echo $value1['q_detail']."<br />";
$i++;
$qno=$value1['q_id'];
$query1=mysql_query("select * from answer where ans_id=$qno");
if(!$query1)
{
echo mysql_error().'query failed';
}
while($value2=mysql_fetch_array($query1))
{
$opt=$value2['option1'];
$opt1=$value2['option2'];
$opt2=$value2['option3'];
$opt3=$value2['correct'];
echo "<input type=\"radio\" value=\"$opt\" name=\"radio_$ans\">";
echo "<span class=\"margin\">$opt</span>";
echo "<input type=\"radio\" value=\"$opt1\" name=\"radio_$ans\">";
echo $opt1." ";
echo "<input type=\"radio\" value=\"$opt2\" name=\"radio_$ans\">";
echo $opt2." ";
echo "<input type=\"radio\" value=\"$opt3\" name=\"radio_$ans\">";
echo $opt3." <br /><br />";
$ans++;
}
}
echo"<input type=\"submit\" name=\"submit\" value=\"submit\">";
echo "</form>";
I've added the if(isset($_POST)) and before the name I've added some text, because a name as a integer, can be used as a integer index in PHP. Array's can be called like
$ar = array("Name" => "VALUE");
echo $ar[0]; // Outputs VALUE
echo $ar["Name"]; // Outputs VALUE
Will both output "VALUE". So what you're trying to do. Is getting the value of index 1 instead of key 1.
You have to use $_POST['actual radiobutton name'], i. e. whatever the content of $ans is at the time of the echoing.
You can also debug your form after submitting by using this code:
echo "<pre>";
print_r($_POST);
echo "</pre>";
This will show you the contents of the $_POST data so you can see if values are being passed correctly.
Harmiih really helped me with my script (http://stackoverflow.com/questions/7510546/html-form-name-php-variable). Basically I have a table with questions. The form retrieves the questions from the table and then I need the selected answers to go to answer.php. Everything is working with the radio butttons but with the check boxes it's only sending the last selected checkbox. Can someone please help me?
form
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' AND q_type = 'mr' ORDER BY RAND() LIMIT 5";
$result1=mysql_query($sql1);
echo "<form method='post' action='answer.php'>";
while($row1 = mysql_fetch_array($result1))
{
$test_name=$row1['test_name'];
$q_nr=$row1['q_nr'];
$q_type=$row1['q_type'];
$question=$row1['question'];
$option1=$row1['option1'];
$option2=$row1['option2'];
echo "<P><strong>$q_nr $question</strong><BR>";
if ($q_type != 'mr') {
if($option1!="") {
echo "<input type='radio' name='question[$q_nr]' value='$option1'>$option1<BR>";
} else {
echo '';
}
if($option2!="") {
echo "<input type='radio' name='question[$q_nr]' value='$option2'>$option2<BR>";
} else {
echo '';
}
} else {
if($option1!="") {
echo "<input type='checkbox' name='question[$q_nr]' value='$option1'>$option1<BR>";
} else {
echo '';
}
if($option2!="") {
echo "<input type='checkbox' name='question[$q_nr]' value='$option2'>$option2<BR>";
} else {
echo '';
}
}
echo "<BR>";
echo "<BR>";
echo "</p>";
}
echo "<input type='submit' value='Send Form'>";
echo "</form>";
answer.php
<?php
//Key is $q_nr and $answer is selected $option
foreach($_POST['question'] as $key => $answer) {
echo $key;
echo $answer;
}
?>
You can use this as name:
name="question[$q_nr][]"
This will make sure you return an array containing all values of the selected checkboxes.
You need to have different name values in checkboxes.
For example name='question1[$q_nr]' and name='question2[$q_nr]'. The same name works only with grouping elements witch radio buttons are.
Or passing them as arrays:
name='question[$q_nr][1]' and name='question[$q_nr][2]'
I currently have a guestbook style thing that users post comments. Their username is stored in a cookie when logged on, and when a post is submitted their username is stored alongside their post in a mySQL database. I'm trying to remove the delete button next to the comment if the user logged in is not the one that posted it. Here is the nonworking code:
<?php
$username = $_COOKIE['sqlusername'];
mysqlLogin();
$sql = mysql_query("SELECT * FROM `posts`");
$sqlCnt = mysql_num_rows($sql);
if($sqlCnt != 0) {
echo "<table align='center'><tr><td class='tdno'><u><H4>Message</H4></u></td><td class='tdno'><u><H4>Poster</H4></u></td><td class='tdno'><u><H4>Time</H4></u></td></tr>";
while($row = mysql_fetch_array($sql)) {
if($row['username'] != $username) {
echo "<script type=\"text/javascript\">";
echo "document.getElementById('delete').innerHTML = \"\";";
echo "</script>";
}
$id = $row['id'];
echo "<form action='delete.php' method='POST'>";
echo "<tr><td>";
echo $row['message'];
echo "</td><td>";
echo $row['poster'];
echo "</td><td align='center' width='10'>";
echo $row['date'];
echo "<td align='left' width='1'>";
echo "<input type='hidden' name='id' value='$id'>";
echo "<span id='delete'><input type='submit' class='submit' value='Delete'></span>";
echo "</td></tr>";
echo "</form>";
}
echo "</table>";
} else {
echo "<div align='center'>Sorry, no posts found!</div>";
}
?>
Any thoughts?
Try:
if ($username == $row['poster']) {
echo "<input type='hidden' name='id' value='$id'>";
echo "<span id='delete'><input type='submit' class='submit' value='Delete'></span>";
} else {
echo " "
}
maybe its the issue with your browser and javascript. Try this :
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById(id).style.display = 'none';
}
else {
if{ // IE 4
document.all.id.style.display = 'none';
}
}
else your logic looks fine(assuming you are storing the username and posts properly in database.)