I want to pass values from my php code (in the same page) to my html - so I could print it out nicely
here is my php function (it's in a while cause it needs to print out 3 lines from a text)
if(sizeof($words)==1)
{
$single = new single;
$docres = $single->find($words);
$dir = "source";
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
echo fgets($handle);
//this is what i need to print in my html
$input = $_POST['input'];
$counter++;
}
}
}
}
and here is my html
<html>
<head>
<title>serach engine</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code' >
// <input type="value" name="input" value="<?php echo $input; ?>">
</center>
</form >
//I would like to print it out here
</div>
</body >
</html >
I searched over the web and saw a solution using $_POST but it didn't work for me...
You could just append it to a new variable and echo it out in the html.
For example:
while($counter < 3) {
echo fgets($handle);
//this is what i need to print in my html
$input .= $_POST['input'] . "<br />";
// You could also do:
// $input .= "<li>" . $_POST['input'] . "</li> "
// For a list item
$counter++;
}
And then echo it in the html:
</form>
<?php echo $input; ?>
</div>
Note: You did not increment your $counter in the while loop.
Related
I'm new to php and here's my code for a number guessing game. Since I don't know how to define a random number, I chose the number myself, 80. I'm trying to store all the guesses prior to the right one, and after the right guess, print them out on the screen. But I can't seem to be able to get it right since it only prints only the last guess before the right one.
Any help is appreciated!
<html>
<head>
</head>
<body>
<?php
$allguesses = array();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_POST["tmn"] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
array_push($allguesses,$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
foreach($allguesses as $x){
echo "<input type ='hidden' name = 'tmn[]' value=' ".$x . " '>";
}
?>
</form>
</body>
</html>
Sessions seem the best for where you are in your learning curve.
The session allows the normal stateless http protocol to remember things between each submission of a form or forms. So we will save each guess in an array of guesses in the SESSION, which in PHP is an array as well.
<?php
session_start(); // create a session, or reconnect to an existing one
if( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["guess"]) ) {
$_SESSION['guesses'][] = $_POST["guess"]; // keep an array of guesses
// $t = $_POST["guess"]; no need for extra variables on the stack
$sayi = 80;
if($sayi > $_POST["guess"]){
echo 'Guess higher';
}elseif($sayi == $_POST["guess"]){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_SESSION['guesses'] as $guess){
echo $guess . ',';
}
$_SESSION['guesses'] = array(); // clear the old guesses out
}else{
echo 'Guess lower';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Removed uneeded codes.
Changed method of showing previous guesses with the below code.
echo implode( ", ", $_POST["tmn"] ); // cleaner
This block handles storing previous guesses into an array that is used for displaying previous guesses.
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
Fixed previous version of below block of code so that hidden <inputs> of previous guesses are outputted properly..
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
Updated Code:
<html>
<head>
</head>
<body>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
echo implode( ", ", $_POST["tmn"] );
}else{
echo 'Guess lower';
}
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
</form>
</body>
</html>
For random numbers you can use rand($min, $max). to store the guesses you can use the global variable $_SESSION.
<html>
<head>
</head>
<body>
<?php
//start session (needed to use the $_SESSION variable)
start_session();
if($_SERVER["REQUEST_METHOD"] == "POST"){
//if empty -> initalize array
if (empty ($_SESSION['allguesses']){
$_SESSION['allguesses'] = array ()
}
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
//echo all guesses from $_SESSION variable
foreach($_SESSION['allguesses'] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
//push in $_SESSION variable
array_push($_SESSION['allguesses'],$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
I have two input fields in PHP form. The fields need to be saved to array and the output should have word lenght of each words next to it in brackets. Also need to evaluate which input field 1 or 2 has longest word and how many words are in each fields. It shows error during execution. syntax error, unexpected end of file
Screenshot 1 Screenshot 2
<!DOCTYPE html ">
<html>
<head>
<meta charset="UTF-8">
<title> Two Input field compare PHP </title>
</head>
<body>
<?php
echo "<br/>";
if (isset($_POST['submit'])) {
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
//example $input1 = "Learning the PHP";
//example $input2 = "Counting words and showing(7) like this word<< ";
if (empty($input1)) {
echo "You need to enter both fields !";
}
if (empty($input2)) {
echo "You need to enter both fields !";
}
echo $input1;
echo $input2;
$inputarr1 = explode(" ", $input1);
$inputarr2 = explode(" ", $input2);
$longestlenghtarr1 = $longestlenghtarr2 = 0;
$arraylength1 = sizeof($inputarr1);
$arraylength2 = sizeof($inputarr2);
$longest1 = $longest2 = 0;
for ($x = 0; $x < arraylength1; $x++) {
echo $inputarr1[$x] . " < " . strlen($inputarr1[$x]) . " > ";
if (strlen($inputarr1[$x]) > $longest1) {
$longest1 = strlen($inputarr1[$x]);
}
}
for ($y = 0; $y < arraylength2; $y++) {
echo $inputarr2[$y] . " < " . strlen($inputarr2[$y]) . " > ";
if (strlen($inputarr2[$y]) > $longest2) {
$longest2 = strlen($inputarr2[$y]);
}
}
if ($longest1 > $longest2) {
echo "<br/> The field 1 input has longest word of lenght " . $longest1." characters !";
}
if ($longest2 > $longest1) {
echo "<br/> The field 2 input has longest word of lenght " .$longest2." characters !";
}
if ($arraylength1 > $arraylength2) {
echo "<br/> The field 1 input has more words";}
if ($arraylength2 > $arraylength1) {
echo "<br/> The field 2 input has more words";
}
echo "<br/>";
?>
<div>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
Input Text 1 <br/>
<input type="text" name="input1" /><br/>
Input Text 2 <br/>
<input type="text" name="input2" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
</body></html>
Probably wrong variable name - it should cause something like Undefined index 'input1' error.
Try replace $POST_ with $_POST so you should have
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
So I have the following code.
My main.html form lets me enter a value (a price for pc) and when I submit it calls the pcs.php script which displays all my pcs under the given value/price.
But I want to have an checkbox beside the information displayed by the script. ie
<br>alienware, 3000, gtx760 checkbox <br> asus rog, 2500, radeodhdxxxx checkbox <br>
and so on).
//main.html
<BODY>
<FORM METHOD="POST" ACTION="pcs.php" >
<INPUT TYPE='textbox' NAME='mypc' VALUE='' >
<INPUT TYPE="SUBMIT" NAME="Button" VALUE="Hit me">
</FORM> </BODY> </HTML>
//pcs.php
<?php
$dd = $_POST['mypc'];
$filename = "computer.txt";
$filepointer = fopen($filename,"r");
$myarray = file ($filename);
for ($mycount = 0; $mycount < count($myarray); $mycount++ )
{
$apc = $myarray[$mycount];
$price = getvalue($apc,1);
$part = explode(',', $apc);
//print $price ."<br>";
//print $str ."<br>";
if ($str <$dd )
{
for($pcount = 0; $pcount<3; $pcount++) {
print $part[$pcount] ."<br>";
}
print "<br>";
}
}
function getvalue ($text, $commaToLookFor)
{
$intoarray = explode(",",$text);
return $intoarray[ $commaToLookFor];
}
// fclose ($filepointer);
?>
<p>
</body>
</html>
// computer.txt file
alienware, 3000, gtx760<br>
asus rog, 2500, radeonhdxxx<br>
alienware, 5000, gtx titan<br>
In pcs.php you'll just need to modify your for loop to look something like:
// Create form
print '<form method="post" action="script_to_post_to.php">';
for ($mycount = 0; $mycount < count($myarray); $mycount++) {
$apc = $myarray[$mycount];
$price = getvalue($apc,1);
$part = explode(',', $apc);
if ($str < $dd) {
for($pcount = 0; $pcount<3; $pcount++) {
print $part[$pcount] ."<br>";
}
// Add checkbox and name with product type
print '<input type="checkbox" name="' . getvalue($apc, 2) . '" />';
print "<br>";
}
}
// Provide form submission button and close form element
print '<input type="submit" value="Submit" />';
print '</form>';
You'll have a form with each element having a checkbox and the ability to respond to the list of checked items in "script_to_post_to.php".
Hey this problem may look really easy to solve but i can't find any solution, my dropdown isn't saving
<?php
// the relative path to the file
$fname = "Erros1.txt";
$fname2 = "Comentarios.txt";
// read in the file if present
if(file_exists($fname)) $txt = file_get_contents($fname);
if(file_exists($fname2)) $Comentarios = file_get_contents($fname2);
// if the user pushes the submit button
if(isset($_POST["Comentarios"])){
$Comentarios = $_POST["Comentarios"]; // get the entered content
file_put_contents($fname2,$Comentarios); // write the content to the file
}
if (isset($_POST["dropdown"])) {
// cast to integer to avoid malicious values
$dropdown = (int)$_POST["dropdown"];
}
?>
<form method="post" action="#">
<textarea name = "txt" cols = "120" rows = "20">
<?php echo $txt; ?>
</textarea>
<textarea name = "Comentarios" cols = "120" rows = "10">
<?php echo $Comentarios; ?>
</textarea>
// here is the dropdown
<select name="dropdown";>
<?php
for ($x=1; $x<=4; $x++) {
echo '<option value="' . $x . '">' . $x . '</option>' . PHP_EOL;
}
echo $_POST['dropdown']
?>
</select>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Only my Comentarios Box is saving, maybe i need to change the submit or create another form
I'm doing form in php but I have some problem.
First I will have 3 different form in the same page.
What I want is only 1 form appear and then with the answer a second form will appear and so on.
The answer of the form will be display on the same page.
For now my first form work and after get the answer go to the 2nd form but I want to submit the 2nd form the problem appear.
It delete the answer of my first form and don't do anything (everything start like I am in my first form).
I try to find the problem but can't have idea about how to solve it.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1?
<input type="number" name="nbtemplate" min="1" max="30">
<input type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php
if(!isset($submitbutton1)) {
if (!empty($_POST['nbtemplate']) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for ($i = 1; $i <= $Nnbtemplate; $i++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
if(isset($submitbutton1) && !isset($submitbutton2)) {
if (!empty($_POST['nbtime']) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST['nbtime'];
for ($j = 1; $j <= $nbtime; $j++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time" name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
}
}
?>
That is some gnarly code you got there, brother. This is a really simple task when handled with some javascript. Then you can have a single post to your php. I like using the jQuery framework so here's a couple links I found quickly: this one and this one
Example code in response to comment about building form elements dynamically:
<html>
<head>
<!-- load jquery library -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<form action="toyourpage.php">
How Many?:
<input type="text" name="number" id="number">
<div id="add"></div>
</form>
<!-- javascript go -->
<script type="text/javascript">
$(document).ready(function()
{
$('input#number').keyup(function()
{
var num = $(this).val(); // get num
if(!isNaN(num)) // check if number
{
$('div#add').html(''); // empty
for(i = 1; i <= num; i++) // add
{
$('div#add').append('New Field ' + i + ': <input type="text" name="next_' + i + '" id="next' + i + '"><br>');
}
}
else
{
alert('Valid number required');
}
});
});
</script>
</body>
</html>
I did some changes on Your code, and have tested, it works.
You had any mistakes in your {} brackets and if conditions. Also as I commented I added extract($_POST).
<?php
extract ( $_POST );
if (! isset ( $submitbutton1 ) && !isset($submitbutton2)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1? <input type="number" name="nbtemplate" min="1" max="30"> <input
type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php ;
}
if (isset ( $submitbutton1 )) {
if (! empty ( $_POST ['nbtemplate'] ) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST ['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or
die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for($i = 1; $i <= $Nnbtemplate; $i ++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
}
}
if ( isset ( $submitbutton2 )) {
if (! empty ( $_POST ['nbtime'] ) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST ['nbtime'];
for($j = 1; $j <= $nbtime; $j ++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time"
name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
?>