foreach value from input form - php

please help me. i have a problem with my code.
This is code input.php :
<form method="POST" action="simpan.php">
NIM : <input type="text" required placeholder="input NIM" name="nim"/><br/>
Name : <input type="text" required placeholder="input name" name="nama"/><br/>
score : <input type="number" required placeholder="input score between 0-100" name="score"/><br/><input type="submit" value="OK"/>
This is code simpan.php :
<?php
session_start();
$_SESSION['nim'][] = $_POST['nim'];
$_SESSION['nama'][] = $_POST['nama'];
$_SESSION['nilai'][] = $_POST['score'];
header("location:index.php")
?>
and This is code show.php :
<?php
session_start();
foreach($_SESSION as $key)
{
foreach($key as $data => $value)
{
echo "NIM : ",$value." ", "Name : ",$value." ", "Score : ",$value." ";
}
}
?>
the result :
enter image description here
And the problem is I want to show the input with format
Nim:
Name:
score:
example = nim:01 name: john score:90
What should I change in show.php in order to appear according to the above format?
thanks :)

#Arif Maulana just change your show.php to like below hope this is what you want:
<?php
session_start();
$echoString = "";
foreach($_SESSION as $key => $sessionArr){
if($key == "nama"){
$echoString .= "name : ";
}
else if($key == "nilai"){
$echoString .= "score : ";
}
else{
$echoString .= $key." : ";
}
foreach($sessionArr as $value)
{
$echoString .= $value." ";
}
}
echo $echoString;
?>

Please check the below example i did https://3v4l.org/CcOOK
<?php
$_POST['nim'] = 'Hrllo';
$_POST['nama'] = 'Data';
$_POST['score'] = '33';
$_SESSION['nim'][] = $_POST['nim'];
$_SESSION['nama'][] = $_POST['nama'];
$_SESSION['score'][] = $_POST['score'];
$string = '';
foreach($_SESSION as $main_key => $key)
{
foreach($key as $data => $value)
{
$string .= $main_key . ":" . $value . ' ';
}
}
$string = rtrim($string, ' ');
echo $string;

Related

php how to do a loop to calculate score for a quiz website

i am creating a quiz website using php where there are 4 questions for users to answer. there is a home page before this for them to choose either math or lit that they wish to do.
after selecting the subject, user need to answer the question and submit their answer, then the php code will calculate their score and count the number of correct/wrong answers.
<ArrayquesAns.php> is the array of questions and answers
it looks something like this, there are 2 array in this php, 1 is math question and another 1 is lit question
and here is the main code where it will generate questions from the question pool randomly. i also tried to put in the code to calculate score
<html>
<body>
<?php
require_once 'ArrayQuesAns.php'; //retrieve array of ques
$_SESSION["subject"] = $_GET['subject']; //suppose to put value when session starts
$_SESSION["name"] = $_GET['name'];
$subject = $_SESSION["subject"];
$name = $_SESSION["name"];
$url = "displayScore.php?name=" . $name . "&subject=" . $subject . "&";
if ($subject == "mathematics") { //math session
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
$MathquesRand = array(); //New array to contain the 4 random rows
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?> </h1>
<p>Hello <?= $name ?>! You may start your quiz !<p>
<hr>
<?php foreach ($MathquesRand as $qtsno => $value) { ?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
} else { //Lit Section
$LitQues_key = array_rand($Litques, 4);
$LitquesRand = array();
$i = 0;
foreach ($LitQues_key as $key) {
$LitquesRand[$i] = $Litques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?></h1>
<p>Hello <?= $name ?> ! You may start your quiz !<p>
<hr>
<?php foreach ($LitquesRand as $qtsno => $value) {
echo $value["ques"], " = \t";
?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
}
?>
<!--Exit-->
<button type="button">EXIT</button>
</body>
</html>
i think this part is where it has issue
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
the code should match user input answer with array question/answer to see if the answer is correct. every correct question will *5 and every wrong answer will *3 (the formula is in the code).
i am not sure if i place the code in the wrong bracket hence its not working or there is some logic error or should i run the code to find the score in a separate php?
after user submit their answer, it will redirect to another page that display their score and number of correct/wrong answers like this
score display html
Based on your original version of the MC test, please find below a working version:
To make it simple, I have removed the "Name" and "Subject" of the form to demonstrate the necessary coding.
You can still use the array_rand to draw 4 random questions
However, after the questions are displayed to the student (and student can input the answer) and clicked "Submit Attempt", the page will remember the random questions drawn - I have used a trick :- to store the questions randomly drawn into a hidden input box
The system will compare the student's submitted answer with that of the correct answer and determine whether it is correct or wrong, and show the score
To fix the "undefined array" errors you encountered, I applied the isset function on places relating to the $_GET variables. (Actually these are warnings, not errors, but it is for sure a good practice to use isset)
<?php
//require_once 'ArrayQuesAns.php'; //retrieve array of ques
$Mathques=array(
1=> array('no'=>1, 'ques'=>"3+1", 'ans'=>"4"),
2=> array('no'=>2, 'ques'=>"3+3", 'ans'=>"6"),
3=> array('no'=>3, 'ques'=>"3+4", 'ans'=>"7"),
4=> array('no'=>4, 'ques'=>"3+5", 'ans'=>"8"),
5=> array('no'=>5, 'ques'=>"3+6", 'ans'=>"9"),
6=> array('no'=>6, 'ques'=>"3+7", 'ans'=>"10"),
7=> array('no'=>7, 'ques'=>"3+8", 'ans'=>"11"),
8=> array('no'=>8, 'ques'=>"3+9", 'ans'=>"12"),
9=> array('no'=>9, 'ques'=>"3+10", 'ans'=>"13"),
10=> array('no'=>10, 'ques'=>"3+11", 'ans'=>"14")
);
if (! isset($_GET["draw"])) {
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
}
$MathquesRand = array(); //New array to contain the 4 random rows
if (! isset($_GET["draw"]) ) {
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
}
?>
<?php
if (isset($_GET["draw"]) && $_GET["draw"] !="") {
$pieces = explode(",", $_GET["draw"]);
$index=0;
while ($index < count($pieces)) {
if ($pieces[$index]!=""){
$MathquesRand[] = $Mathques[$pieces[$index]];
}
$index++;
}
}
?>
<form action="" method="get">
<?php
$correct=0;
$wrong=0;
?>
<h1> Section : Mathematics </h1>
<p>Hello ! You may start your quiz !<p>
<hr>
<?php
$pool="";
$ii=1;
foreach ($MathquesRand as $qtsno => $value) {
$pool.= $value["no"]. ",";
?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans<?php echo $ii; ?>"
<?php if (isset($_GET["userans".$ii]))
{
echo " value='" .$_GET["userans".$ii] . "'>" ;
} else { echo ">" ; }
?>
<?php if (isset($_GET["userans".$ii]) && $_GET["userans".$ii]==$value["ans"]) {
$correct++;
} else {
$wrong++;
}
?>
<br>
<?php
$ii++;
}
?>
<input name=draw type=hidden value="<?php echo $pool; ?>">
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
$score = ($correct * 5) - ($wrong * 3);
?>
<?php if (isset($_GET["draw"])) { ?>
<font color=red>Result:</font>
<br>Correct:<?php echo $correct;?>
<br>Wrong:<?php echo $wrong;?>
<br>Score:<?php echo $score;?>
<?php } ?>
To share my experience (I have coded such Multiple Choice Q & A functions many times) , in future if you want to do similar thing, please consider using
database to store the drawn questions ;
use ajax to compare the input data with the correct data stored in the db, instead of using form submission

Can only get two values using foreach loop on a $_POST form

In the below code I am building a form from a database. The problem is when using foreach ($_POST as $response => $answer) I only get two variables $response['response'] and $response['response_id']. why am I not able to get more i.e. response, name and value?
// Question form
echo "<style>.error{color: red;}
</style>";
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">';
$legend = $responses[0]['category'];
echo "<fieldset>";
echo"<legend>$legend</legend>";
foreach ($responses as $response) {
if ($legend != $response['category']) {
$legend = $response['category'];
echo "</fieldset>";
echo "<fieldset>";
echo"<legend>$legend</legend>";
var_dump($response);
}
echo '<label '.($response['response'] == NULL ? 'class="error"' : '').' for ="'.$response['response_id'].'">'.$response['name'].':</label>';
echo "Love <input ".($response['response'] == 1 ? 'checked = "checked"' :'')." type='radio' '.'id='".$response['response_id']."' name='".$response['topic_id']."' value='1'></input> or";
echo "Hate <input ".($response['response'] == 2 ? 'checked = "checked"':'')."type='radio' id='".$response['response_id']."' name='".$response['topic_id']."' value='2'></input><br />";
}
echo "</fieldset>";
echo"<br /><input type = 'submit' submit = 'submit'>";
echo "</form>";
// php action on form
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
var_dump($_POST);
echo "post <br />";
foreach ($_POST as $response => $answer) {
var_dump($_POST);
$query = "UPDATE mismatch_response SET response = '$answer' WHERE response_id = '$response' ";
mysqli_query($dbc, $query);
//var_dump($answer);
}

how to remove a letter according to a particular position

i have two php files.
1st is displayPhone.php
<!DOCTYPE html>
<html>
<?php
$labels=array("first_name"=>"First Name",
"last_name"=>"Last Name",
"phone"=>"Phone");
?>
<body>
<h3>please enter your phone number below</h3>
<form action='savePhone2.php' method='POST'>
<?php
//loop that displays the form field
foreach($labels as $field =>$value)
{
echo "$field <input type='text' name='$field' size='65' maxlenghth='65'/><br/>";
}
echo "<input type='submit' value='submit phone number'/>";
?>
2nd is savePhone2.php
<?php
$labels=array("first_name"=>"First Name",
"last_name"=>"Last Name",
"phone"=>"Phone");
?>
<body>
<?php
foreach($_POST as $field =>$value)
{
if(empty($value))
{
$blank_array[]=$field;
}
elseif(preg_match("/name/i",$field))
{
if(!preg_match("/^[A-Za-z' -]{1,50}$/",$value))
{
$bad_format[]=$field;
}
}
elseif($field=="phone")
{
if(!preg_match("/^(\(\d+\)|\d+\-)?\d{10,20}$/",$value))
{
$bad_format[]=$field;
}
}
}
if(#sizeof($blank_array)>0 or #sizeof($bad_format)>0)
{
if(#sizeof($blank_array)>0)
{
echo "<p>input";
foreach($blank_array as $value)
{
echo " $labels[$value]";
}
echo "</p>";
}
if(#sizeof($bad_format)>0)
{
echo "<p>invalid format";
foreach($bad_format as $value)
{
echo $labels[$value];
}
echo "</p>";
}
//redisplay form
echo "<hr/>";
echo "enter phone number";
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>";
foreach($labels as $field =>$label)
{
$good_data[$field]=strip_tags(trim($_POST[$field]));
echo "$label <input type='text' name='$field' size='65' maxlength='65' value='$good_data[$field]'/><br/>";
}
echo "<input type='submit' value='submit phone number'/>";
exit();
}
else
{
$user='root';
$host='localhost';
$password='root';
$dbname='pet';
$cxn=mysqli_connect($host,$user,$password,$dbname) or die("can't connect to server");
foreach($labels as $field =>$value)
{
$good_data[$field]=strip_tags(trim($_POST[$field]));
$good_data[$field]=mysqli_real_escape_string($cxn,$good_data[$field]);
}
$check_exist="SELECT ";
foreach($labels as $field =>$value)
{
$check_exist.=$field.",";
}
$check_exist=preg_replace("/,{3}/","",$check_exist);
$check_exist.=" FROM data WHERE ";
foreach($good_data as $field =>$value)
{
$check_exist.=$field."="; $check_exist.="'$value'".",";
}
echo $check_exist;
Iam having a problem that i don't know how to remove the decimals at phone, and at phone='0123456789087', on this query:
SELECT first_name,last_name,phone, FROM data WHERE
first_name='sloth',last_name='dig',phone='0123456789087',
The easiest way to take control of trailing characters when build a string from list is by joining prepared elements of an array.
Change
$check_exist="SELECT ";
foreach($labels as $field =>$value)
{
$check_exist.=$field.",";
}
to
$check_exist="SELECT ";
$fieldArray = array();
foreach($labels as $field =>$value)
{
$fieldArray[] = $field;
}
$check_exist .= join(', ', $fieldArray);
In the same manner you could change
foreach($good_data as $field =>$value)
{
$check_exist.=$field."="; $check_exist.="'$value'".",";
}
to
$whereArray = array();
foreach($good_data as $field =>$value)
{
$whereArray[] = $field . "=" . "'$value'";
}
$check_exist .= join(' AND ', $whereArray);
This should produce SELECT first_name, last_name, phone FROM data WHERE
first_name='sloth' AND last_name='dig' AND phone='0123456789087' - notice that after where conditions are joined by AND rather than a comma ,.
And of course this will work only if $good_data and $labels are not empty.
Not sure if I understand your question.
Do you mean that there are decimal points (periods, dots) in the phone number when retrieved from the database and you wish to remove them?
phpFiddle here
If so:
<?php
$n = "123.456.7890";
$o = str_replace(".", "", $n);
echo $o;
$x = "123,456,7890";
$y = str_replace(",", "", $x);
echo $y;
You may continue to use your code
foreach($good_data as $field =>$value)
{
$check_exist.=$field."="; $check_exist.="'$value'".",";
}
and clean $check_exists at the end
$check_exists = rtrim($check_exists, ",");

Apple warranty check script

After looking for some Ruby scripts i tried to write on PHP with some help the script.
My Problem is now that I am not sure if the jSon Objects are correct cause I dont know the source for it now.
My Question is if I am making anything wrong with jSon in PHP? If not than the Objects of the Sources are wrong.
<?php
$sn = isset($_GET['sn']) ? $_GET['sn'] : '';
if($sn)
{
$url = 'https://selfsolve.apple.com/warrantyChecker.do?sn='.$sn . "&country=USA";
$json = file_get_contents($url);
$json = substr($json, 5, -1);
$json_obj = json_decode($json);
if(isset($json_obj->ERROR_CODE))
{
echo $json_obj->ERROR_DESC;
}
else
{
echo "$json_obj->PROD_DESCR <img src=\"$json_obj->PROD_IMAGE_URL\" alt=\"\"><br>";
echo"Product Description: $json_obj->PROD_DESCR <br>";
echo"Purchase date: $json_obj->PURCHASE_DATE <br>";
echo"Warranty exp date: $json_obj->COVERAGE_DATE <br>";
}
}
?>
<form action="" method="get" accept-charset="utf-8">
<p><input name="sn" value="<?=$sn?>"><input type="submit" value="Lookup serial"></p>
</form>
Another way I have tried to do it is
<?php
$sn = $argv[1];
$data = json_decode(file_get_contents(
"https://selfsolve.apple.com/warrantyChecker.do?sn=". $sn . "&country=USA"));
echo "Product Description" .$data->PROD_DESCR."\n";
echo "Coverage for " . $sn . " ends on " . $data->COVERAGE_DATE . "\n";
?>
<?php
$sn = isset($_GET['sn']) ? $_GET['sn'] : '';
if($sn)
{
$url = 'https://selfsolve.apple.com/warrantyChecker.do?sn='.$sn . "&country=USA";
$json = file_get_contents($url);
//This line you are splitting the json form then it wont work
$json = substr($json, 5, -1);
$json_obj = json_decode($json);
if(isset($json_obj->ERROR_CODE))
{
echo $json_obj->ERROR_DESC;
}
else
{
echo "$json_obj->PROD_DESCR <img src=\"$json_obj->PROD_IMAGE_URL\" alt=\"\"><br>";
echo"Product Description: $json_obj->PROD_DESCR <br>";
echo"Purchase date: $json_obj->PURCHASE_DATE <br>";
echo"Warranty exp date: $json_obj->COVERAGE_DATE <br>";
}
}
?>

PHP or HTML Form Validation

I want to validate an HTML form in either HTML or PHP. By validate, I mean ensuring there is at least 1 character of text entered into each of the 2 textboxes. And either only alpha numeric characters entered, or have something that ensures that any punctuation doesn't end up with "/" before it.
At the moment my form is made up of 2 php pages (copied below), and then posted to a txt file.
I'm either after some (very basic) instructions on how to do it, or suggestions on my script below.
//HTML
<form style="" method="post" action="addtopic2.php">
Topic:<input name="topic" id="topicbox" maxlength="100" type="text"><br>
Outline: <textarea input wrap="nowrap" rows="10" cols="120"
name="outline"></textarea>
<br><input name="submit" value="Submit" type="submit">
</form>
//HTML
<?php
$t = "Topic:";
$o = "Outline:";
$topic = $_POST['topic'];
$outline = $_POST['outline'];
$data = "$t $topic | $o $outline |\n";
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
fclose($fh);
?>
//ATTEMPTED TO USE FOLLOWING, BUT DOESNT SEEM TO WORK WHEN INSERTING INTO EITHER PAGES.
<?php
if($_POST['Submit'] == "submit")
{
$errorMessage = "";
if(empty($_POST['topic']))
{
$errorMessage .= "<li>A topic needs to be entered</li>";
}
if(empty($_POST['outline']))
{
$errorMessage .= "<li>An outline needs to be entered</li>";
}
$vartopic = $_POST['formtopic'];
$varoutline = $_POST['formoutline'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<?php
if (isset($_POST['topic']) && isset($_POST['outline'])) {
$topic = trim($_POST['topic']);
$outline = trim($_POST['outline']);
}
else {
echo '<p>Fill the form</p>';
}
?>
Try
$file = "users.txt";
$errorMessage = array ();
if ($_POST ['Submit'] == "submit") {
if (empty ( $_POST ['topic'] )) {
$errorMessage [] = "A topic needs to be entered<";
}
if (empty ( $_POST ['outline'] )) {
$errorMessage [] = "An outline needs to be entered";
}
if (count ( $errorMessage ) == 0) {
$data = $_POST ['topic'] . "|" . $_POST ['outline'] . "\n";
$fh = fopen ( $file, "a" );
fwrite ( $fh, $data );
fclose ( $fh );
} else {
print ("<p>There was an error with your form:</p>\n") ;
print ("<ul>") ;
foreach ( $errorMessage as $error ) {
print "<li>" . $error . "<li>";
}
print ("</ul>") ;
}
}
// To Read Your File
$content = file ( $file );
print ("<p>File Details</p>\n") ;
foreach ( $content as $info ) {
list ( $topic, $outline ) = explode ( "|", $info );
print ("<ul>") ;
print "<li>Topic: " . $topic . "<li>";
print "<li>Outline:" . $outline . "<li>";
print ("</ul>") ;
}
Try this (single file) solution:
<form style="" method="post">
Topic:<input name="topic" id="topicbox" maxlength="100" type="text" value='<?= $_REQUEST['topic'] ?>><br>
Outline: <textarea input wrap="nowrap" rows="10" cols="120" name="outline"><?= $_REQUEST['outline'] ?></textarea>
<p/>
<input name="submit" value="Submit" type="submit">
</form>
<?php
if ($_REQUEST['submit'] !== 'submit')
{
exit;
}
if ($_REQUEST['topic'] == '')
{
echo "<p>Missing Topic.</p>\n";
exit;
}
if ($_REQUEST['outline'] == '')
{
echo "<p>Missing Outline.</p>\n";
exit;
}
$t = "Topic:";
$o = "Outline:";
$topic = $_POST['topic'];
$outline = $_POST['outline'];
$data = "$t $topic | $o $outline |\n";
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
fclose($fh);
?>

Categories