So here's my code in getting an input from a user on how many questions (multiple choice) he/she would like to make:
Multiple choice: <input type = "text" name="MC"><br>
<input type = "submit" name = "confirm" value = "Confirm">
After that, this is the code of how many questions the system will generate:
<?php
if(isset($_POST['confirm'])){
$MC = $_POST['MC'];
echo "<form method = 'POST' name = 'items' action ='createquestions.php'>";
$items = 1;
for ($x = 1; $x <= $MC; $x++) {
echo "Question Number $items:"; echo "<input type = 'text' name = 'questions[]' style='width: 500px'><br><br>";
echo "A. "; echo "<input type = 'text' name = 'ans1[]'>";
echo "B. "; echo "<input type = 'text' name = 'ans2[]'><br>";
echo "C. "; echo "<input type = 'text' name = 'ans3[]'>";
echo "D. "; echo "<input type = 'text' name = 'ans4[]'><br>";
echo "Correct Answer: "; echo "<input type = 'text' name ='cans[]'><br><br>";
$items++;
}
echo "<input type ='submit' name = 'save' value = 'Save'>";
echo "</form>";
}
?>
<?php
The problem is that it will only save the last input of the user.
For example, I have inputted 2 in the Multiple choice: --textbox here--
This code will generate 2 questions, 8 choices, 2 cans = correct answer but it will only save the 2nd question, answers, and the correct answer. the system won't get the record of the 1st question, answer, and the correct answer.
Here is the code where I would insert it on the database:
<?php
if(isset($_POST['save'])){
$user_id = $_SESSION['id'];
$questions = $_POST['questions'];
$ans1 = $_POST['ans1'];
$ans2 = $_POST['ans2'];
$ans3 = $_POST['ans3'];
$ans4 = $_POST['ans4'];
$cans = $_POST['cans'];
foreach($questions as $q){
echo "<input type = 'hidden' value = '$q'>";
}
require_once('xcon.php');
$query = "INSERT INTO mcq (mc_id, user_id, questions, ans1, ans2, ans3, ans4, cans)
VALUES ('NULL','$user_id','$q','$ans1','$ans2','$ans3','$ans4','$cans')";
$result = mysql_query($query);
if($result){
echo 'Insert Success!';
}
else{
echo 'Error';
}
}
?>
When you save you should be running through a loop again. Try this maybe?
<?php
if(isset($_POST['save'])){
$user_id = $_SESSION['id'];
require_once('xcon.php');
foreach ($_POST['questions'] as $key => $question){
$ans1 = $_POST['ans1'][$key];
$ans2 = $_POST['ans2'][$key];
$ans3 = $_POST['ans3'][$key];
$ans4 = $_POST['ans4'][$key];
$cans = $_POST['cans'][$key];
echo "<input type = 'hidden' value = '$question'>";
$query = "INSERT INTO mcq (mc_id, user_id, questions, ans1, ans2, ans3, ans4, cans)
VALUES ('NULL','$user_id','$question','$ans1','$ans2','$ans3','$ans4','$cans')";
$result = mysql_query($query);
if($result){
echo 'Insert Success!<br>';
}else{
echo 'Error<br>';
}
}
}
?>
According to this post you should use:
echo "Question Number $items:"; echo "<input type = 'text' name = 'questions' style='width: 500px'><br><br>";
echo "A. "; echo "<input type = 'text' name = 'ans[]'>";
echo "B. "; echo "<input type = 'text' name = 'ans[]'><br>";
echo "C. "; echo "<input type = 'text' name = 'ans[]'>";
echo "D. "; echo "<input type = 'text' name = 'ans[]'><br>";
echo "Correct Answer: "; echo "<input type = 'text' name ='cans'><br><br>";
And this:
$ans1 = $_POST['ans'][0];
$ans2 = $_POST['ans'][1];
$ans3 = $_POST['ans'][2];
$ans4 = $_POST['ans'][3];
Explanation
You only need to post ans[] repeatedly , and not
ans1[], ans2[], ans3[]... in order to get an array like
$_POST['ans'][0], $_POST['ans'][1]...
or you can use
ans1, ans2, ans3
(without brackets []) to read as
$_POST['ans1'], $_POST['ans2'], $_POST['ans3']...
You are using element naming in a strange way, you are using array, but still use numbers. Try generating like this:
for ($x = 0; $x <= $MC; $x++) {
echo "<input type = 'text' name = 'questions[$i]'>";
echo "A. <input type = 'text' name = 'ans[$i][A]'>";
echo "B. <input type = 'text' name = 'ans[$i][B]'><br>";
echo "C. <input type = 'text' name = 'ans[$i][C]'>";
echo "D. <input type = 'text' name = 'ans[$i][D]'><br>";
echo "Correct Answer: <input type = 'text' name ='cans[$i]'><br><br>";
}
Then you'll get the following results in your $_POST:
[
"questions" => [
0 => "question1",
...
]
"ans" => [
0 => [
"A" => "answer A",
"B" => "answer B",
"C" => "answer C",
"D" => "answer D",
]
...
]
"cans" => [
0 => "A",
....
]
]
Which is easily processed with a foreach:
foreach ($_POST['questions'] as $key => $question) {
// $question == 'question1';
$answers = $_POST['ans'][$key]; // array of answers
$solution = $_POST['cans'][$key];
}
Related
pls help me..
im trying to input value with this code :
$attr_checklist = $flagTriwulan[$i] ? "hidden" : '';
echo "<td class='basicTable padding10 textCenter' style=\"font-size:13px;\"> <center>
<input type='radio' ".$attr_checklist." name='nilaikuantitatif[<?php echo [$i]; ?>]'
value='5'></center>
<br>".$skala5[$i]." </br>
</td>";
this when im submit :
if(isset($_POST['cmdSubmit']))
{
$aspek_a = $_POST['aspek_a'];
$nilaikuantitatif = $_POST['nilaikuantitatif'];
$multi = new MultipleIterator();
$multi->attachIterator(new ArrayIterator($aspek_a));
$multi->attachIterator(new ArrayIterator($nilaikuantitatif));
foreach($multi as $key => $value)
{
list($aspek_a, $nilaikuantitatif) = $multi->key();
list($aspek_a, $nilaikuantitatif) = $value;
$queryInsAspek = "insert into kpi_kuantitatif
(idDivisi,idDepartment,idEmployee,idPenilai,bulan,tahun
,aspek, nilaikuantitatif,submitBy, inputDT)
select".$idDivisi.",".$idDepartment.",".$idEmployee_C.",".$idEmployee.",".$bulan.",".$tahun.",'". $aspek_a."','".$nilaikuantitatif."',".$userID.", getdate()";
$resultInsAspek = sqlsrv_query($conn, $queryInsAspek);
}
so, i want if hidden then the value nilaiKuantitatif becomes 0, but if not hidden the value nilaiKuantitatif becomes 5
sorry for my bad english..pls help
Assuming that you mean you want the value in this code to be 0 in the event $attr_checklist == "hidden"...
$attr_checklist = $flagTriwulan[$i] ? "hidden" : '';
echo "<td class='basicTable padding10 textCenter' style=\"font-size:13px;\"> <center>
<input type='radio' ".$attr_checklist." name='nilaikuantitatif[<?php echo [$i]; ?>]'
value='5'></center>
<br>".$skala5[$i]." </br>
</td>";
Change this...
value=`5`
To...
value='<?php echo $attr_checklist == "hidden" ? 0 : 5; ?>'
A variable $irn input by the users, I need to pass the variable $irn one by one to a SQL and display the result in GR textbox after clicking the button
Generate Result, I want to split the $irn to an array so I can pass it one by one to the SQL query.
I tried mb_split and preg_split
<?php
include "big2gb.php";
ini_set('default_charset', 'utf-8');
$result = $_GET["listIRN"];
$irn = $_POST["irn"];
$serverName = "192.168.4.75";
$connectionInfo = array( "Database"=>"SAFHKG", "UID"=>"sa1", "PWD"=>"Azsxdc11", "CharacterSet" => "UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if($conn){
//echo "connect DB success!!!<br />";
}
else
{
//echo "successfully failed!!!<br />";
die(print_r(sqlsrv_errors(),true));
}
//find irn
$sql="Select Top 1
[Expression] = CONCAT(OFFICIALNUMBER, ' for ', TITLE, ' in Class ', LOCALCLASSES)
From CASES
INNER JOIN OFFICIALNUMBERS On CASES.CASEID = OFFICIALNUMBERS.CASEID
Where NUMBERTYPE IN ('R', 'A') and CASES.IRN = ('".$array[$i]."')
Order By
CASE
When NumberType = 'R' then -2
When Numbertype = 'A' then -1
End";
echo"
<table>
<form action='test22.php' method='post'>
<tr>
<td>IRN:</td>
<td>
<input type='text' id='txtIRN' value='' style='text-transform:uppercase' >
<input type='button' value='Add IRN' onClick='addIRN()' name=''/>
<input type='submit' value='Genarate Result' id='GR' name=''/>
</td>
</tr>
<tr><tr><tr>
<td><td>
<textarea id='listIRN' name='irn' rows='40' cols='30' >
</textarea><textarea id='GR' rows='40' cols='80' ></textarea>
</td></td>
</tr></tr></tr>
</form>
</table><br/>";
echo"
<script type='text/javascript'>
function addIRN(irn) {
var IRNText = document.getElementById(\"txtIRN\").value;
var IRNList = document.getElementById(\"listIRN\").value;
var irn = IRNList + '\\n' + IRNText;
document.getElementById(\"listIRN\").value = irn.trim().toUpperCase();
}
</script>";
//////////////////your entered//////////////////*
echo "<p>You entered:<p>";
$array = mb_split('\\n', $irn);
foreach($array as $line)
{
$array = explode('\s', $irn);
echo "$line\n";
}
//////////////////////////////////////////////
print_r ($array);
//echo $array[3];
//echo $array[0];
for ($i = 0; $i <= 20; $i++)
{
$result = sqlsrv_query($conn, $sql );
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOc) )
{
echo " ". $row["Expression"] ." <br />";
}
}
$conn->close();
?>
strong text
User input will be like TM1150CN31 TM2846CN35 TM2855CN35 TM2865CN35 TM2874CN43 TM3367CN05
You can use explode function like below
$var = 'TM1150CN31 TM2846CN35 TM2855CN35 TM2865CN35 TM2874CN43 TM3367CN05';
$array = explode(' ', $var);
Out put will be like
Array
(
[0] => TM1150CN31
[1] => TM2846CN35
[2] => TM2855CN35
[3] => TM2865CN35
[4] => TM2874CN43
[5] => TM3367CN05
)
I have in a array a table like this:
cid plugin lang_id name father
1 Newspage 1 Actualidad 1
1 Newspage 2 News 1
2 Newspage 1 Tecnologia 1
2 Newspage 2 Tech 1
3 Newspage 1 Deportes 1
3 Newspage 2 Sports 1
4 Newspage 1 Ocio 1
In this example there are two languages (1:Spanish and 2:English) but admin can add more languages
I want do a "modify category" section and group it by CID with input boxes for each language if language its missed i want display a empty input for add the missed language.
Something like this:
http://i.imgur.com/fGCUgKc.png
My actual bad code its this:
$content = "<div class='catlist'>";
$content .= "<p>{$LANGDATA['L_NEWS_MODIFIED_CATS']}</p>";
$query = $db->select_all("categories", array ("plugin" => "Newspage", "lang_id" => 1));
while ($cat_grouped = $db->fetch($query)) {
$content .= "<form id='cat_mod' method='post' action=''>";
$content .= "<div>";
foreach ($langs as $lang) {
if ($lang['lang_id'] == $cat_grouped['lang_id']) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$cat_grouped['name']}' />";
} else {
$query2 = $db->select_all("categories", array ("plugin" => "Newspage", "cid" => "{$cat_grouped['cid']}", "lang_id" => "{$lang['lang_id']}"));
if($db->num_rows($query2) <= 0) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='' />";
} else {
$other_lang_cat = $db->fetch($query2);
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$other_lang_cat['name']}' />";
}
}
}
$content .= "<input type='hidden' name='cid' value='{$cat_grouped['cid']}' />";
$content .= "<input type='submit' name='ModCatSubmit' value='{$LANGDATA['L_NEWS_MODIFY']}' />";
$content .= "</div></form>";
}
$content .= "</div>";
This:
$db->select_all(...);
mean
$db->select_all("table", $WHERE, ...)
I want to retrieve all content in one query and do the work in php
My actual code its clearly very bad and assumed lang_id=1 exists for each entry and do few query's huh!
My old code use "GROUP BY cid" for the first query and not need to use "lang_id=1" but after a system upgrade that line give the error:
reported: Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column
and not want to use again that.
any idea the best way for do that?
I don't know what your database library is, so I'm writing a pseudo like code.
First, I would use a pagination to limit the database queries, for example 10/20 phrases for each page. So the query would be:
SELECT * FROM language_phrases WHERE cid IN (
SELECT DISTINCT cid FROM language_phrases WHERE plugin = 'Newspage'
LIMIT 0,10
)
then I would use the data from database first to get the cid values:
$cid = array();
$strings = array();
while($row = $db->fetch($result))
{
if(!in_array($cid,$row["cid"]))
{
$cid[] = $row["cid"];
}
$strings[]= array(
"cid" => $row["cid"],
"lang_id" => $row["lang_id"],
"name" => $row["name"],
"father" => $row["father"]
);
}
Then I would have the table and the distinct cid's in this page in my buffer. Then PHP will do the rest:
foreach($cid as $idx=>$key)
{
$values = array_filter($strings,function($d) use ($key) {
return $d["cid"] == $key;
});
// build the form with the $values array.
}
This problem give a headache but i made another version that work and only one query.
I will check later the Taha Paksu version/way (thanks!)
$content = "<div class='catlist'>";
$content .= "<p>{$LANGDATA['L_NEWS_MODIFIED_CATS']}</p>";
$query = $db->select_all("categories", array ("plugin" => "Newspage"), "ORDER BY cid");
$cats = [];
$catsids = [];
while ($cats_row = $db->fetch($query)) {
$cats[] = $cats_row;
$catsids[] = $cats_row['cid'];
}
$catsids = array_unique($catsids);
$foundit = 0;
foreach ($catsids as $catid) {
$content .= "<form id='cat_mod' method='post' action=''>";
$content .= "<div>";
foreach ($langs as $lang) {
foreach ($cats as $cat) {
if (($catid == $cat['cid']) && ($cat['lang_id'] == $lang['lang_id'])) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$cat['name']}' />";
$foundit = 1;
}
}
if ($foundit == 0) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='' />";
}
$foundit = 0;
}
$content .= "<input type='hidden' name='cid' value='$catid' />";
$content .= "<input type='submit' name='ModCatSubmit' value='{$LANGDATA['L_NEWS_MODIFY']}' />";
$content .= "</div></form>";
}
I have 3 PHP files, in select.php file you have to select the number of forms that you want.. the form contain 3 input fields.
as below:
<form method="post" action="index.php" >
Continue insertion with <select name="counters" id="insert_rows">
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
</select>
rows
<input type="submit" value="Go" />
</form>
After selecting the number of insertions, it will pass the number to index.php which is contain:
<?php
echo "<form method = 'POST' action = 'process.php'>";
for($counter = 0; $counter < $_POST['counters']; $counter++)
{
echo "Service Name: <input type = 'text' name = 'name[]' class = 'class_name'/><br/>";
echo "Service Version : <input type = 'text' name = 'version[]' class = 'class_name'/><br/>";
echo "Service type : <input type = 'text' name = 'type[]' class = 'class_name'/><br/>";
}
echo "<input type = 'submit' value = 'SEND'/>";
echo "</form>";
?>
the third file process.php contain
<?php
$name = array();
$version = array();
$type= array();
$name = $_POST['name'];
$version = $_POST['version'];
$type= $_POST['type'];
for($counter = 0; $counter < sizeof($name); $counter++)
{
echo "service_name #".($counter + 1).": ".$name[$counter]."<br />";
echo "service_version #".($counter + 1).": ".$version[$counter]."<br />";
echo "service_type #".($counter + 1).": ".$type[$counter]."<br />";
}
?>
and after i pass the value to it, it shows the data correctly as below
service_name #1: noway
service_version #1: v1
service_type #1: Private
service_name #2: bandar
service_version #2: v2
service_type #2: Public
so my question is : how to create a function in 'process.php' file to insert all these values into the database.
I created a table called 'services' contain these columns "name,version,type"
I will be waiting for your support.
thank you
I would recommend to save the first submitted count value in an hidden input in the second form, then you will be able to loop through that and insert your data
<?php
echo "<form method = 'POST' action = 'process.php'>";
for($counter = 0; $counter < $_POST['counters']; $counter++)
{
echo "Service Name: <input type = 'text' name = 'name[]' class = 'class_name'/><br/>";
echo "Service Version : <input type = 'text' name = 'version[]' class = 'class_name'/><br/>";
echo "Service type : <input type = 'text' name = 'type[]' class = 'class_name'/><br/>";
}
echo '<input type="hidden" name="cntr" value="'.$_POST['counters'].'" />'
echo "<input type = 'submit' value = 'SEND'/>";
echo "</form>";
?>
Now in your process.php you will have:
if (!empty($_POST['cntr'])) {
$query = 'INSERT INTO services (name, version, type) VALUES ';
for ($x = 0; $x < $_POST['cntr']; $x++)
{
$query .= "('".mysqli_escape_string($_POST['name'][$x])."','"
.mysqli_escape_string($_POST['version'][$x])."','"
.mysqli_escape_string($_POST['type'][$x]).
"'),";
}
$query = substr_replace($query, '', -1);
mysqli->query($query);
}
Whatever I prepared is just a sample you can modify it base on your changes
I am really having a hard time figuring out why if(isset($_POST['next'])) isn't working. How can I call something like that within a function?
function questions($result){
$options = array('A','B','C','D','E');
echo "Please click 'Next'";
echo "<p class = 'button'><input type='submit' name='next' value='Next'/></p>";
while($row = $result->fetch_assoc()){
if(isset($_POST['next'])) {
echo "<h4>".$row['question']."</h4>";
foreach($options as $option){
$text = $row[$option];
if($text)
echo "<br/><input type = 'radio' name = 'ans' value = '$option'>".$text."<br/>";
}
echo "<p class = 'button'><input type='submit' id='submit' class = 'answer' name='submitAns' value='Submit' /></p>";
if(isset($_POST['submitAns'])){
$answer = $row['answer'];
if($_POST('ans') == $answer) {
echo "<h4>Correct!</h4>";
} else {
echo "<h4>Incorrect. Correct answer is: ".$answer."</h4>";
}
echo "<p class = 'button'><input type='submit' id='next' name='next' class = 'answer' value='Next' /></p>";
}
}
}
if(isset($_POST['next'])){
echo "End of questions for this exam";
}
}
Checking to see if a variable exists (isset) and checking to see whether a variable actually contains something (empty) are two different things. Try this:
function questions($result){
$options = array('A','B','C','D','E');
echo "Please click 'Next'";
echo "<p class = 'button'><input type='submit' name='next' value='Next'/></p>";
while($row = $result->fetch_assoc()){
if($_POST && isset($_POST['next']) && !empty($_POST['next'])) {
// ....
}