Inserting Array values from form into mysql - php

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

Related

Get PHP Select Value no sql commands

Here's my HTML code:
<form method = "get" action = "PHPFile.php">
Type:<select name = "type">
<option value = "1">1</option>
<option value = "1">2</option>
<option value = "1">3</option>
</select>
Your Type:<input type = "text" name = "yourType" value = "$varType;">
Fee:<input type = "text" name = "fee" value = "$varFee;">
</form>
I want to get the value of my select "type" and pass it to my textbox "yourType".
And each type options has corresponding fees:
For Type 1 = 250
Type 2 = 90
Type 3 = 90
Here is my Php code:
<?php
$varType = $_GET("type");
if($varType == 1){
$varFee = 250;
}
else {
$varFee = 90;
}
?>
But I always get an parse error on getting the value of $varType
<?php
$varType = null;
if(isset($_GET['type'])) {
$varType = $_GET['type'];
if($varType == 1){
$varFee = 250;
}
else {
$varFee = 90;
}
}
?>
<form method = "get" action = "PHPFile.php">
Type:<select name = "type" ONCHANGE="if(this.value!='-1') location = this.options[this.selectedIndex].value; else return;">
<option value = "-1">---</option>
<option value = "?type=1">1</option>
<option value = "?type=2">2</option>
<option value = "?type=3">3</option>
</select>
Your Type:<input type = "text" name = "yourType" value = "<?php echo $varType; ?>">
Fee:<input type = "text" name = "fee" value = "<?php echo $varFee; ?>">
</form>

getting the value of text field executed through a for loop using php

I have created 3 text fields which are displayed through a for loop. Now my concern is how will I get the values inputted to those text fields. Here's the code. Thank you.
<?php
echo '<form method = "post" action = "http://localhost:8080/sample.php">';
for($a = 0; $a < 3; $a++){
echo '<input type = "text" name = "box"></br>';
}
echo'<input type = "submit" name = "submit" value = "submit">';
if(isset($_POST['submit'])){
$square = $_POST['box'];
echo $square;
}
echo'</form>';
?>
Like Lucia Angermüller suggested you could do something like this
<?php
echo '<form method = "post" action = "http://localhost:8080/sample.php">';
for($a = 0; $a < 3; $a++){
echo '<input type = "text" name = "box' . $a . '"></br>';
}
echo'<input type = "submit" name = "submit" value = "submit">';
and them you could access $_POST['box0'] or $_POST['box1'].
Hope this helps. Good Luck :)

Getting all array values in loop

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];
}

Passing information using post method without session variables

I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>

PHP Math Pythagoras

Okay, I've coded this pythagoras-solver kind of thing, and I was wondering any ways I could improve it, or make it more efficient?
<?php
$sides = array('1' => 'Hypotenuse',
'2' => 'Adjacent',
'3' => 'Opposite');
function createSideDropdown($name) {
global $sides;
$option = "<select name='".$name."'>";
if(!empty($sides)) {
foreach($sides as $id => $sideDesc) {
$option .= "<option value='".$id."'>".$sideDesc."</option>";
}
} else {
die("Error fetching sides!");
}
$option .= "</select>";
echo $option;
}
try {
if(!empty($_POST['submit'])) {
if(empty($_POST['val1']) || empty($_POST['val2'])) {
throw new Exception("Please enter an integer in both boxes.");
}
if(!is_numeric($_POST['val1']) || !is_numeric($_POST['val2'])) {
throw new Exception("One of the numbers you entered is not a valid integer.");
}
$val1 = $_POST['val1'];
$val2 = $_POST['val2'];
$val1numtype = $_POST['val1type'];
$val2numtype = $_POST['val2type'];
$val1nametype = $sides[$val1numtype];
$val2nametype = $sides[$val2numtype];
if($val1numtype == $val2numtype) {
throw new Exception("The two sides of the triangle must be different");
}
if($val1nametype == "Hypotenuse" || $val2nametype == "hypotenuse") {
// work out a small side
$bignum = max($val1, $val2);
$smallnum = min($val1, $val2);
$sqTotal = ($bignum * $bignum) - ($smallnum * $smallnum);
$total = sqrt($sqTotal);
echo $bignum."² - ".$smallnum."² = ".$sqTotal."<br />
√".$sqTotal." = ".$total.$_POST['mes'];
} else {
// work out the hypotenuse
$sq1 = $val1 * $val1;
$sq2 = $val2 * $val2;
$sqTotal = $sq1 + $sq2;
$total = sqrt($sqTotal);
echo $val1."² + ".$val2."² = ".$sqTotal."<br />
√".$sqTotal." = ".$total.$_POST['mes'];
}
echo "<br /><br />"; // Seperate the working out from the input
}
} catch(Exception $e) {
echo $e->getMessage()."<br/><br/>";
}
?>
<form method='POST' action='index.php'>
Value 1: <input type='text' name='val1' />
<?php createSideDropdown("val1type"); ?>
<br /><br />
Value 2: <input type='text' name='val2' />
<?php createSideDropdown("val2type"); ?>
<br />
<select name="mes">
<option name="mm">mm</option>
<option name="cm">cm</option>
<option name="m">m</option>
<option name="cm">km</option>
</select>
<br />
<input type="submit" name="submit" />
</form>
?>
Well, one thing you can certainly do is:
HTML on its own and PHP on its own - separate that. And then, I would continue having a look at the rest.
Also, you could do your exceptions with JavaScript - I mean, use JavaScript to parse the text fields and write the errors with JavaScript. Rather than always submitting the form. - Still you should parse the fields in PHP as well.
Then, make a class out of it and make a proper documentation of it such as
/**
* This method does bla
* #param Int a
*/
Don't use globals - could be done with class attributes.

Categories