Array of forms in PHP - php

First, thanks for taking a look at this. I am trying to create an array of forms that acts as a dynamically sized results list. From the results that were given the user can click 'detail' (a submit button) to get further information on the result which is why I am attempting to create an array of forms. Here is what I had tried, which compiled but the buttons aren't doing anything. Any help would be great :)
<?php
session_start();
?>
<html>
<head>
</head>
<body>
<?PHP
$numbers=array(1,2,3,4,5);
$listsize=count($numbers);
for($currentnum=0;$currentnum <$listsize;$currentnum ++){
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="button" value="Submit" name="button<?PHP echo $currentnum?>" />
</form>
<?PHP
echo "<br/>";
}
if(isset($_POST['button'.$currentnum])){
echo "You choose ".$currentnum;
}
?>
</body>
</html>
This is really just meant to demonstrate what I am trying to do (thought that would be easier without functions out of scope of question).

Try changing the HTML for the button:
<input type="button" value="Submit" name="button<?PHP echo $currentnum?>" />
Should be:
<input type="submit" value="Submit" name="button<?PHP echo $currentnum?>" />
Close bracket for your for loop so that your check is inside it:
<?PHP
echo "<br/>";
}
if(isset($_POST['button'.$currentnum])){
echo "You choose ".$currentnum;
}
?>
Should be:
<?php
echo "<br/>";
if(isset($_POST['button'.$currentnum])){
echo "You choose ".$currentnum;
}
}
?>
If you learn to indent your code you'll find these kinds of bugs much easier to spot!
Other than that you're good to go...

You need to change your input types from 'button' to 'submit' so that they submit the forms, then you need to move
if(isset($_POST['button'.$currentnum])){
echo "You choose ".$currentnum;
}
inside of the for loop

Related

How to get Multiple Inputs?

I want to get Multiple Inputs and use them later when Press Submit Button
<!DOCTYPE html>
<html>
<head>
<title>Class Details</title>
</head>
<body>
<?php
$noOfSections=0;
$sectionNameArray= array();
$sectioerr="";
if($_SERVER["REQUEST_METHOD"]=="POST"){
if(!empty($_POST["noOfSections"]))
$noOfSections = $_POST["noOfSections"];
else
$sectioerr="Must Enter Number of Sections";
}
?>
<form action="classdetails.php" method="POST">
<p>Enter Number of Sections : </p>
<input type="text" name="noOfSections">*<?php echo $sectioerr?>
<input type="submit" name="submit" value="Enter"><br>
</form>
<form action="classdetails.php" method="POST">
//Thats the real area about which I am Asking Questions
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){//it is USED to prosses THE STATEMETS BELOW only when the above Submit Button is pressed
echo "<p>Enter Names of Sections : </p><br>";
for($x=0;$x<$noOfSections;$x++){
echo "Enter Name of Section No. ".($x+1)."<br>";
echo "<input type=\"text\">*";
}
echo "<input type=\"submit\" name=\"submitnames\"><br>";
}
?>
</form>
</body>
</html>
I want to Get Multiple Inputs when I press Submit Button Having name attribute "submitnames"
Try adding [] to the end of your dynamic input names
echo "<input type=\"text\" name=\"names[]"\>*";
Edit :Thanks to Magnus Eriksson for pointing out my mistake in the comments.

php allow submit if variable is true

Newbie here, and self-taught in PHP. I have a questionnaire where each question has 2 answers, and users can add any combination of numbers to each, as long as they equal, i.e. 10. So far 2 questions (will be more) so each question's answers should equal 10, therefore total submitted values should equal 20. I can't find a way to only allow submit if these conditions are met. I would really appreciate any help.
Currently using this for testing purposes:
<input type="submit" value="Check!" name="check"/>
...at the bottom.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<?php
// Adding stuff
if(isset($_POST['check']))
{
$q1total=$realist[1]+$idealist[1];
$q2total=$realist[2]+$idealist[2];
$grandtotal=$q1total+$q2total;
}
?>
<body>
<form method="post">
Q1: <input type="text" name="realist[1]"/> <input type="text" name="idealist[1]"/>
<?php echo $q1total; ?>
<br>
Q2: <input type="text" name="realist[2]"/> <input type="text" name="idealist[2]"/>
<?php echo $q2total; ?>
<br>
<br><br>
Grand total: <?php echo $grandtotal; ?>
<br><br>
<input type="submit" value="Check!" name="check"/>
</form>
</body>
</html>
I'm also a self-taught PHP "newbie" as you describe it. I would honestly create a seperate PHP file that checks if the conditions are met.
Your form would be:
<form method="post" action="yourfile.php">
And in the php file:
$realist1 = $_POST["realist\[1\]"];
$idealist1 = $_POST["idealist\[1\]"];
$realist2 = $_POST["realist\[2\]"];
$idealist2 = $_POST["idealist\[2\]"];
if ($realist[1]+idealist[1]== 10 && $realist[2]+idealist[2] == 10)
{
echo "<button value='correct'/>";
}else{
echo "<button value='incorrect' disabled/>";
}
Obviously you have to adjust some stuff but hopefully this can help.

Can I self submit back to a textarea box?

I am able to create a textarea box that will accept text and store that text to the $_POST super global, but I can't get the text to "come back" to the box once I submit it. (The form is self submitting). If I run a simple echo on the submitted data, however, it displays fine (as shown toward the end of the script below.
<!DOCTYPE html> <body> <?php require("Connection_to_WS.php");
echo ("<form action='Edit_Thread_Description.php' method='post'>");
IF (ISSET($_POST['revised_thread_descr'])) {
$revised_thread_descr=($_POST['revised_thread_descr']);
ECHO "Edit the Revised_Thread_Description here: <br> <textarea name='revised_thread_descr' rows='5' cols='50' value= $_POST[revised_thread_descr]"; // Fails to return any text on Submit.
?><p></textarea></p><br><?php
}
ELSE {$revised_thread_descr= '[some default]';
ECHO "Edit the Revised_Thread_Description here: <br> <textarea name= 'revised_thread_descr' rows='5' cols='50' value= $revised_thread_descr";
?><p></textarea></p><br><?php
}
ECHO '<br>';
echo $_POST['revised_thread_descr']; // Succeeds in returning POST text from the textarea box upon Submit (but outside of the textarea box).
ECHO '<br>';
echo "Click 'Submit': <input type='Submit' name='submit' value='Submit'/>";
echo '<br>';
mysqli_close($connection);
?>
</body> </html>
Doing the same sort of thing was a breeze using "<input type", but I've sunk hours into getting <textarea to cooperate. I I'd be grateful for any assistance.
As Ann Sophie said, there is no "value" property on the textarea element
(https://www.w3schools.com/tags/tag_textarea.asp)
if you want to dynamically append content to it, you can use :
<?php if (isset($_POST['revised_thread_descr'])): ?>
<textarea><?= $_POST['revised_thread_descr'] ?></textarea>
<?php else: ?>
//
Note that you have to echo it, in my example I used alternative syntax,
(http://php.net/manual/fr/control-structures.alternative-syntax.php)
which I think is much more cleaner when you works with PHP + HTML
<?= XXX ?> is short for <?php echo XXX; ?>
I botched a response via 'comment', above. This continues that comment:
This code works, but won't repopulate the box with remarks submitted back to the script via the POST super global.
IF(ISSET($_POST['revised_thread_descr'])):
$revised_thread_descr=($_POST['revised_thread_descr']); ?>
<p> Revised_thread_descr - Edit here:</p><textarea
name='revised_thread_descr' rows='5' cols='50'
<p></textarea></p><br>
<?php
ELSE:
$revised_thread_descr= '[some default]'; ?>
<p> Revised_thread_descr - Edit here:</p><textarea name= 'revised_thread_descr' rows='5' cols='50'
<p></textarea></p><br>
<?php
ENDIF;
echo "Click 'Submit': <input type='Submit' name='submit' value='Submit'/>";
echo '<br>';
mysqli_close($connection);
?>
</body>
</html>
This code, with just a slightly different placement of the <p> tags, gobbles up and displays all html material that comes after the closing </textarea> tag.
IF(ISSET($_POST['revised_thread_descr'])):
$revised_thread_descr=($_POST['revised_thread_descr']); ?>
<p> Revised_thread_descr - EDIT HERE:</p><p><textarea name= 'revised_thread_descr' rows='5' cols='50'
</textarea></p><br>
<?php
As in the screenshot of the browser rendering, below.
Thanks, btw, for getting me to try that alternate syntax! Less confusing.
Bless you! I'd given up and was going for a workaround. I put in that tag caret as you suggested and it all worked. Here is the gist of it, with everything working, and the textarea box populating correctly. Thank you so much for your patience and persistence. Tell me it gets easier... .
<!DOCTYPE html> <body>
<?php
echo ("<form action='Textarea_Example.php' method='post'>");
// The first IF only executes after the script has run once and created a POST value. On the second run, the first IF executes and successfully populates the textarea box with the latest POSTed value
IF (ISSET($_POST['revised_thread_descr'])): ?>
<p>Edit current thread description:<p>
<textarea name= 'revised_thread_descr' rows='5' cols='50'>
<?php echo $_POST['revised_thread_descr'] ?>
</textarea>
<?php ELSE:
$revised_thread_descr = 'some default'; ?>
<p>Edit current thread description:<p>
<p><textarea name= 'revised_thread_descr' rows='5' cols='50'>
The textarea box opens with this in it, but only on the first run. Then it successfully switches to the value typed to the textarea box and saved to POST
</textarea>
<?php ENDIF; ?>
</p>
<?php
// here's the submit button
echo "Click 'Submit': <input type='Submit' name='submit' value='Submit'/>";
?>
</body> </html>

Session variable not working

I am using one session variable in my php page. As per my infomation, it is accessible throughout the program and it is, but problem is that it is showing different value for the same variable at different place in php page?
the code is as follows
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form>
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
value becomes different before and after submit button click? Please tell me why it is so?
thanks in advavnce.
You are redeclaring the value of session variable 'x' here
$_SESSION['x'] = $_SESSION['x']+1;
This is why its appearing 1 greater than its initial value.
it is due to the code itself
if(isset($_SESSION['x'])) //It is set
$_SESSION['x'] = $_SESSION['x']+1; //Add 1 to the value
echo $_SESSION['x']."<br>"; return value with +1
Solution
The reason the output is different is the order you echo and update
//Echo
//Update Value
//Echo again
Simple solution would be to move this
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
to above this
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
Also note set the method and the action in the form to make sure it calls itself
<form method="GET" action="[url to itself]">
<input type="submit" name="save" value="save" />
</form>
Do it like this :
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form method="GET" action="">
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
this way the code prints out the same value after submit as it did before.
Either way you try if you print value and change after or change value and print after, when page reloads it will change value. you could add another button called increment and add the following code inside the php :
if (isset($_GET['inc']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
}
and this one inside the form:
<input type="submit" name="inc" value="inc" />
this way youre variable increment when you press the inc button

Displaying Database Query Results

Suppose I have a form. After I submit my form, the data is submitted to dataprocess.php file.
The dataprocess.php file processes the variable sent via form and echoes desirable output.
It seems impossible to echo to a specified div in specified page only using PHP (without using AJAX/JavaScript as well). I do not want to use these because some browsers might have these disabled.
My concern is that I want to maintain the same formatting of the page that contained the form element. I want the form element to be there as well. I want the query result to be displayed below the form.
I could echo exact html code with some modification but that's memory expensive and I want it systematic.
Is it possible to process the form within the same page? Instead of asking another .php file to process it? How does one implement it?
The above is just for knowledge. It will be long and messy to include the PHP script within the same HTML file. Also, that method might not be efficient if I have same process.php file being used by several forms.
I am actually looking for efficient methods. How do web developers display query result in same page? Do the echo all the html formatting? also, does disabling JavaScript disable jQuery/AJAX?
Yes it is possible to process the form on the same page.
<?php
if (isset($POST))
{
//write your insert query
}
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<!-- Your form elements and submit button -->
</form>
<table>
<?php
//your select query in a while loop
?>
</table>
</body>
</html>
But if you choose this technique instead of ajax, you have to refresh all the page for each insert action.
An example
<div id="dialog-form">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<table>
<tr>
<td>Job</td>
<td>
<input type="text" name="job" />
</td>
</tr
</table>
<input type="submit" value="Insert" />
</fieldset>
<input type="hidden" name="doProcess" value="Yes" />
</form>
</div>
<?php
$myQuery= $db->prepare("INSERT INTO Jobs (job) VALUES (:p1)");
if (isset($_POST['doProcess']) && $_POST['doProcess'] == 'Yes')
{
$myQuery->bindValue(":p1", $_POST['job'], PDO::PARAM_STR);
$myQuery->execute();
}
?>
if you really dont want to use ajax (which i think you should). You can do something like this.
<form action="" method="POST">
<input type="text" value="something" name="something_name"/>
<?php
if(isset($_POST['something_name'])){
echo '<div id="display_something_name_if_exists">';
echo $_POST['something_name'];
echo '</div>';
}
?>
</form>
Basically what it does is submits to itself and then if there is a submission (tested with isset), it will echo a div with the correct information.

Categories