Creating HTML Forms from PHP Arrays [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make a form in html that would create radio options bases upon the specified array in PHP.
Code:
<form name="form" action="Test.php" method="get">
<?php
//Creates the Array
$radioButtonArray = array("cat", "dog", "sheep", "moose");
//Length of the Array
$count = count($radioButtonArray);
//Runs for each index.
for($x = 0; $x < $count; $x++)
//Creates a radio button with the specified length
echo "<input=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]} <br>";
?>
</form>
As you can see firstly I open the form tag inside of HTML. Then I create a array with animals names and run a loop through each array index. During each loop it should create a new radio button and then make a new line as directed by the echo.
The issue is that when I run the file the output should be for example:
(RADIO BUTTON HERE) cat
(RADIO BUTTON HERE) dog
(RADIO BUTTON HERE) sheep
(RADIO BUTTON HERE) moose
Instead I get:
cat
dog
sheep
moose
I know that it is reading the echo line so the error would have to be located on that line. I am very new to PHP and decently familiar with HTML so a simple but detailed explanation of what I did wrong or what I should do would be very greatly appreciated. Thank you in advance.
How to Fix:
I did not correctly enter the format for declaring a input.
//Change This
echo "<input=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]}<br>";
//To This
echo "<input type=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]}<br>";

There is small error on the echo statement. HTML radio button should read
but your output statement reads instead.
Hence you should change
echo "<input=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]} <br>";
To
echo "<input type=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]} <br>";

Try this:
echo "<input type=\"radio\" name=\"Animal\" value=\"{$radioButtonArray[$x]}\">{$radioButtonArray[$x]} <br>";
You are not specifying the input type.

input=\"radio\" should be input type=\"radio\"

It should be input type="radio" not input="radio"

Related

PHP table creation with name and score [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am having some serious trouble for some reason with creating a basic PhpMyAdmin database and making a page with a scoreboard. There will be a game that you play, and when you're done you can input a score and your name using basic form elements. When you press submit the page will reload and you will be able to see the top ten scores, ranked by highest first.
My issue is that I have no idea where to start with this. I have just started Php and don't wish for anything crazy. I have the ~/php/db_connect.php set up correctly already; I just need to make the function work.
How do you recommend I go through with this? Example code is extremely helpful.
I know the first response is "what have you tried?" and I haven't tried much.
This is what I have right now:
// define variables and set to $name = $myArray[0];
$babyinfo = fgets($myfile);
$myfile = scoreboard-dk;
$myArray = explode(',', );
$score = $myArray[1];
$name = $myArray[2];
$insertStmt = "INSERT INTO scoreboard-dk ('score','name') VALUES ('$score','$name')";
// Inserting Babynames into database
$db->query($insertStmt);
?>
<form action=" $db;?>" method="post">
Name: <input type="text" name="name" value=" echo $name;?>" required><br>
Score: <input type="text" name="score-dk" value=" echo $score;?>" required><br>
<input class="btn btn-primary" type="submit">
</form>
<tr> <th scope=row> echo $i;?></th> <td> echo $score;?></td> <td> echo $name;?></td> <td> echo $votes;?></td> </tr>
Thanks in advance.
Ok. First some mistakes you made:
$myfile = scoreboard-dk; isn't working. This way it would be a constant. You need the "$" or quotation marks if it should be a string.
$myArray = explode(',', ); I don't know what you want to do? The second argument is missing. This statement won't work. Second argument has to be a string.
You have to properly escape the query before executing the statement.
You can do this by replacing the following line before building the string:
$score = $db->real_escape_string($myArray[1]);
$name = $db->real_escape_string($myArray[2]);
Furthermore are you sure you use the correct indices for the array access? Counting starts with 0, not with 1.
You can't use PHP code without the opening tags. I thought that you cut that away at the start of the file. You always have to open PHP code blocks with
Perhaps you should search for example code elsewhere. I think stack is more for specific questions. But the code actually shows that you lack of some basic knowledge ... no offense.
The reason people can't help you is that your question is way too broad and everyone will have a different approach about how to implement it.
That being said, here is the pseudo code I would use to implement this. It can be done in a single file. Good luck!
File: score_keeper.php
<?php
error_msg = array
if (form submitted)
$name = name from form
$score = score from form
// Do validation to ensure name and score is as expected.
if name is empty
error_msg[] = 'Name cannot be empty'
if score is not numeric
error_msg[] = 'Score must be numeric'
if empty(error_msg)
// INSERT
// Make sure you use parameterized queries
SQL = INSERT into table (name, score) VALUE (?, ?)
end-if
end-if
// READ top 10
SQL = SELECT name, score FROM table WHERE ...
if !empty(error_msg)
show error_msg
?>
<form method="post">
<input name="name">
<input name="score">
</form>
HTML table
<?php
// output top 10 results

How to name an array after content from a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I've a form tag which sends the name for an array to a function but how can I name my array after this? Ok, code says more than thousand words:
<?php
function dynamic($id, $name, ... ){
...
echo "<select id='$id' name='$name' size='...' multiple>";
...
echo "<select id='$id' name='$name'>";
...
}
?>
<form ... method="post">
<p>
<?php
echo dynamic("dynamic1", "choice1", ...);
?>
</p>
<p>
<?php
echo dynamic("dynamic2", "choice2", ...);
?>
</p>
<p>
<?php
echo dynamic("dynamic3", "choice3", ...);
?>
</p>
<input type="submit" value="send"/>
</form>
I want to create a list where you can select multiple items but for this $name needs ot be an array. The array should named like the second variable. In one case it should be named choice1 in another choice2
Like how do I get from $name = "choice1"; to choice1[]
#edit Added a new line in function to show my problem. somtimes $name needs to be and array and sometimes not
Any ideas?
You are looking to use dynamic variable names, which is possible in PHP, but you need to be careful with this. Production code using this can be difficult to maintain and throw errors quite easily.
Anyway, lets say you have a value in the form $_POST that you want to use as a variable name. You would do so like this.
$id = "gettheidsomewhere";
${$id}[] = "whatever";
Like i said, use this carefully. Dynamic variable names are dangerous and very hard to debug when things break.
If you do not know the value used for $id, then you will need to loop through your post variables and assign them accordingly. I would assume you want to add some extra logic, but here is a basic example.
Using a key value loop you can obtain the name of the post variable, stored as $key and the value. So for $_POST["something"] = "test", when this line is looped over, $key will be "something" and $value will be "test".
foreach ($_POST as $key => $value)
{
${$key}[] = $value;
}

How Can I generate radio buttons based on the number of quiz questions I have?

I'm just starting out with php and wanted to do a fun project to get better with it. I created a text file that starts with the question, then has the answer choices, and then has the answer index:
What does charmander evolve to?#Charmeleon:charizard:squirtle#0
Who is the main character in Pokemon?#Misty:Ash:Brock#1
How can I generate radio buttons based on the number of questions there are?
<?php
$quizStuff = file("quiz1.txt");
foreach ($quizStuff as $questions) {
$questionParse = explode("#", $question);
$answerChoices = explode(":",$questionParse[1]);
echo "$questionParse[0] ? <br />";
foreach ($answerChoices as $answerChoice) {
# create radio button and print answer choice next to it
}
}
?>
Since radio buttons are a type of form, I was thinking that I would have a submit button at the end of the question and the next question would pop up after a user pressed submit. General design input would be great too!
I am not used to making text file as a database but here is what i see a solution. I put a counter to identify which question is where the choices are included.
$ctr = 1;
foreach ($quizStuff as $questions) {
$questionParse = explode("#", $question);
$answerChoices = explode(":",$questionParse[1]);
echo "$questionParse[0] ? <br />";
foreach ($answerChoices as $answerChoice) {
echo "<input type='radio' id='".$answerChoice.$ctr."' name='question$ctr' value='$answerChoice'> <label for='".$answerChoice.$ctr."'>".$answerChoice."</label><br>"
}
}

<textarea> value, vs. innerHTML....in regards to PHP [duplicate]

This question already has answers here:
How to add default value for html <textarea>? [closed]
(10 answers)
Closed 7 years ago.
I was trying to figure out a bug in my CRUD system with a
I want to propagate the text field with previous text for when a user needs to update the text area.
I'm using this code, setting the value to the text I wanted, but it won't work
<?php
echo "<textarea name='text1' value= '".$row['text1']."' class='materialize-textarea'></textarea>";
echo "<label for='text1'>text notes</label>";
?>
any suggestions?
<?php
echo "<textarea name='text1' class='materialize-textarea'>".$row['text1']."</textarea>";
echo "<label for='text1'>text notes</label>";
?>
Passing values in textarea doesnt work. There is no value attribute in textarea. You need to make it as innerHtml of textarea Try Below,
<?php
echo "<textarea name='text1' class='materialize-textarea'>'".$row['text1']."'</textarea>";
echo "<label for='text1'>text notes</label>";
?>

solved: HTML checked checkboxes in a FORM to a file.txt PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So I have a Form with Check Boxes and When I submit the form I want the values of the boxes that are selected to be sent to a text file?
Question: How do I know what boxes are selected and then retrieve those values?
this is my form, it is all automated once someone selects a value from a drop down box
echo '<form action="test.php" method="post">'
sqlCheckbox();
echo '<input type="submit" value="save to text file" name="Save To Text File"'
echo '</form>
sqlCheckbox() does this for each result
echo '<input type="checkbox" name="check[]" value="SQL_QUERY">SQL_QUERY <br>'
I found the solution, this is what i fixed/did.
change 1: changed my checkbox name to an array ([] at the end of name)
change 2: once the submit is clicked it goes to my test.php page
here is my other page code
<?php
echo "saved to file";
$array = $_POST['check'];
information = "";//Justin for the variable Idea
foreach ($array $value) {//turns out only the checked checked boxes get submitted
$information .= $value . "<br>";
}
$file = "test.txt" //Flo draven had this idea
file_put_contents($file, $information, FILE_APPEND | LOCK_EX);
?>
this saves the values that were selected and sends them to the test.txt file, so I now have my sql queries in a text file
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>
instead of "Hello World" , take the contents of your checkboxes.
you can of course define a variable with the path to any file you want to put the contents into.
a better option probably would be :
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
Check out using fopen and fclose on the Php Manual. That opens a file, then you will be able to send the data to it and save it.

Categories