Undefined Offset when looking through an array to display values - php

Hey I am new to PHP and I am trying to take values from the user that were put into a form for a game. Every time the user enters text and clicks submit it should add it to the array. Every time it will show at the bottom of the page all the guesses currently in a ordered list until the user gets the right answer and wins.
<?php
$count =0;
$guesses = array();
if(isset($_POST['submit']))
{
$count = $_POST['count'];
for($r =0; $r < $count; $r++)
{
$guesses[$r] = $_POST['word'];
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "<?php echo $tell; ?>"/>
<input type = "hidden" name = "count" value = "<?php $count +=1;?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
for($t=0; $t < $count; $t++)
{
?>
<li><?php echo $guesses[$t];?></li>
<?php
}
?>
</ol>
I keep getting a Undefined offset: 0. I did some reading and I know it has something to do with either me filling the array wrong or calling the index wrong. Hope you can help show me how to resolve this problem. Thank you.
The output would be similar to:
Your guesses:
1. blue
2. red
etc

Look if you don't want to use Session variable then you have to set the values enter by the user in the hidden input tag. Below is the code you might required to get your specific result:
<?php
$guesses="";
if(isset($_POST['submit']))
{
$guesses= $_POST['count']." ".$_POST['word'];
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "Word"/>
<input type = "hidden" name = "count" value = "<?php echo $guesses;?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
$count = explode(" ", $guesses);
foreach($count as $val)
{
if($val!= ''){
?>
<li><?php echo $val;?></li>
<?php
}
}
?>
</ol>

EDITED:
Problem was that you foremost did not echo the $count in your form, you simply incremented it. So the post variable would be empty. Also, increment it after you add to the array instead of in the post.
<?php
if( !isset( $count ) ){
$count =0;
}
$guesses = array();
if(isset($_POST['submit'])) {
$guesses[$count] = $_POST['word'];
$count++;
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "<?php echo $tell; ?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
for($t=0; $t < count( $guesses); $t++)
{
?>
<li><?php echo $guesses[$t];?></li>
<?php
}
?>
</ol>

Try this code:
<?php
$guesses = array();
if(isset($_POST['submit']))
{
if($_POST['guesses'] != '')
$guesses = explode('|', $_POST['guesses']);
if(trim($_POST['word']))
$guesses[] = trim($_POST['word']);
}
?>
<h3>Guess the word I'm thinking</h3>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="text" name= "word" value="" />
<input type="hidden" name="guesses" value="<?php echo count($guesses)? implode('|',$guesses):''; ?>" />
<input type="submit" name="submit" value="Make a Guess" />
</form>
<ol>
<?php foreach($guesses as $guess) { ?>
<li><?php echo $guess;?></li>
<?php } ?>
</ol>

Related

PHP for loop concatenation

for($i = 1; $i <= 1; $i++) {
$you_item[$i] = ucwords($_POST['you_item'.$i.'']);
$you_item[$i] = "http://steamcommunity.com/market/priceoverview/?appid=570&currency=1&market_hash_name=".$you_item[$i]."";
$you_item[$i] = str_replace(' ', '%20', $you_item[$i]);
$you_item[$i] = file_get_contents($you_item[$i]);
$you_item[$i] = json_decode($you_item[$i], true);
$you_item[$i] = $you_item[$i]['median_price'];
$you_item[$i] = preg_replace("/&#?[a-z0-9]{2,8};/i","", $you_item[$i]);
echo $you_item[$i];
}
the sample site is this http://bit.ly/1gKGoN0
I have a problem on the loop of getting the value from the textboxes
i declared the form like this
<?php for($i=1;$i<=15;$i++){ ?> <input type="text" name="<?php echo
"you_item".$i.""?>" /> <?php } ?>
but the problem now is i cant get the value from the textboxes where i forwarded to $you_item[$i].
the site that i made doesnt have a loop. i coded the $you_item1 upto 15 because i have 15 textboxes.
can someone help me out?
try to change,
<?php for($i=1;$i<=15;$i++){ ?> <input type="text" name="<?php echo
"you_item".$i.""?>" /> <?php } ?>
to
<input type="text" name="you_item[]" />

How preserve my inputs values each time that I refresh my page?

I want to enter a name and a mark. As the mark entered is less or equal to 100, the names and marks entered is to be stored in an associative array when I click the submit button and it should request me to enter another name and marks. But if I enter a mark greater than 100 discarding the name entered, when I click the submit button, the php script should display me all the names and marks previously entered. Here what I have done but I am not getting the desired results. Please help. My code:
<?php
if(isset($_POST['lname']) && isset($_POST['marks'])){
$name = $_POST['lname'];
$marks = $_POST['marks'];
$lists = array($name => $marks);
foreach($lists as $name => $marks){
echo $name . '<br>';
echo $marks;
}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method = "POST">
Name:<br>
<input type = "text" name = "lname"><br><br>
Marks:<br>
<input type = "text" name = "marks"><br><br>
<input type = "submit" value = "Submit">
</form>
You can use session to achieve what you want, see this code:
<?php
session_start();
if(isset($_POST['lname']) && isset($_POST['marks'])){
if($_POST['marks'] > 100) {
$_SESSION['info'][] = array($_POST['lname'] => $_POST['marks']);
}
}
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
foreach($_SESSION['info'][$i] as $name => $marks){
echo '<p>' . $name . '<br>';
echo $marks . '</p>';
}
}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method = "POST">
Name:<br>
<input type = "text" name = "lname"><br><br>
Marks:<br>
<input type = "text" name = "marks"><br><br>
<input type = "submit" value = "Submit">
</form>
You should read some docs about session:
http://php.net/manual/en/intro.session.php
You are posting name and your server side is looking for lname

php code for button counter

Am trying to run a php code which counts button clicks. It increments to 1 and then it doesn't count. here is my code:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
?>
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = post>
<input type = "submit" name = "button" value = "vote" >
</form>
Am not a php expert so can anybody please tell me where am going wrong?
Thanks
Use this php:
<?php
if(isset($_POST["button"])){
$counter++;
echo counter;
}
?>
Also, use this for the opening <form> element
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Try this:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
?>
<form action = "<?php echo $_SERVER["PHP_SELF"]; ?>" method = post>
<input type = "hidden" name = "counter" value = "<?php echo $counter; ?>" />
<input type = "submit" name = "button" value = "vote" />
</form>
Store the count in a session. Note that this stores a separate count for each user. If you want one single count that is shared between all users then you'll need to store it in a database.
<?php
// Start the session
session_start();
// Make sure a session variable exists
if ( !isset($_SESSION['count']) ) {
$_SESSION['count'] = 0;
}
// Check to see if a vote has been submitted
$vote = isset($_POST['button']) ? $_POST['button'] : false;
if ( $vote ) {
// Increment the vote
$_SESSION['count']++;
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<input type="submit" name="button" value="Vote">
</form>

PHP variable returns a null value

I've created a textbox so when the admin types a name and clicks submit, it will shows a list of retrieved data from the database.
<form method="post" action="">
<?php
$teacherName = $_POST['teacherName'];
if ($_POST['submitted'] == 1) {
if($teacherName != ""){
$getName = mysql_query("SELECT name, user_id FROM members WHERE name = '$teacherName'");
$teacherdetails = mysql_fetch_array($getName);
$teachername = $teacherdetails['name'];
$teacher_id = $teacherdetails['user_id'];
if($teachername != ""){
print $teachername . "<br/>";
} else {
print "Give a valid name <br/>";
}
}
}
if ($teachername == ""){ ?>
Teacher name:<input type="text" size="20" name="teacherName"><input type="hidden" name="submitted" value="1"><br/>
<input type="submit" value="Submit" />
<?php $getModule = mysql_query("......");
while ($row2 = mysql_fetch_array($getModule)) { ?>
<input type="checkbox" name="modules[]" value="<?php print $row2["module_id"]?>"/> <?php print $row2["module_name"] . '<br/>'; } ?>
</div><br/> <?php } ?>
<input type="submit" value="Submit" />
</form>
Below I wrote this code (in the same script):
<?php
$modules = $_POST['modules'];
for($i = 0; $i < count($modules); $i++){
$module=mysql_query("INSERT INTO module (module_id,user_id) VALUES ('$modules[$i]','$teacher_id')");
}
?>
but for some reason when I call the variable "$teacher_id" (which is the value I retrieved before from the database. It works fine in the form) it returns nothing. It's null but I can't understand why.
Am I doing something wrong?
First off, put the PHP outside the form tags, at the top.
Secondly, the data you are receiving could be an array; with more than one result set;
do this just incase it it returned as that;
foreach($teacherdetails AS $teacher) {
//also set the values of the variables here
echo $teacher['name'];
echo $teacher['user_id'];
}
Regarding the last bit, is the $teacher_id successfully printing a result?
Also, where is the modules being input and posted from?

How to create isset($_POST['id'.$var]) within loops?

I am trying to create a page where there are several fields and users can comment on each one. To create these fields and text inputs, I am running a while loop with the following html within it:
<form name = "replyform" method = "post" action = "">
<input id = "replytext<? echo $replyID; ?>" value = "replytext<? echo $replyID; ?>" name = "replytext<? echo $replyID; ?>" type="text" class = "span5">
</form>
And then using the following code to call the 'wall_reply()' function, submitting the text values.
if (isset($_POST['replytext'.$replyID])) {
echo wall_reply();//5, $_POST['replytext'.$replyID]);
}
Something's a miss though. Any ideas what could be wrong here?
You have loop to create these form and input?
put the loop inside the form tag, so that only one form will be created with multiple inputs.
this seem to work correctly, use it as your guide ;)
<?php
$maxposts=7;
if (isset($_POST['submit'])){
function wall_reply($id,$text){
echo '<hr />updating id '.$id.' with '.$text;
}
var_dump($_POST);
for ($i=0;$i<$maxposts;$i++){
$replyID = $i;
if (isset($_POST['replytext'.$replyID])) {
wall_reply($i,$_POST['replytext'.$replyID]);//5, $_POST['replytext'.$replyID]);
} else {
echo 'not set';
}
}
}
?>
<form name = "replyform" method = "post" action = "">
<?php
$replyID = 5;
for ($i=0;$i<$maxposts;$i++):
$replyID = $i;
?>
<input id = "replytext<?php echo $replyID; ?>" value = "replytext<?php echo $replyID; ?>" name = "$
<?php endfor; ?>
<input type="submit" name="submit" value="go"/>
</form>

Categories