PHP variable returns a null value - php

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?

Related

PHP: Generating a html table through a form [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 months ago.
This is practice coursework for my Informatics course. We've just started programming in PHP and our task is to program a website that generates tables for the user.
password prompt
ask the user how many rows and columns the table should have
based on the last question; create a form with the same amount of input boxes
generate the table with the input of step 3
I've accomplished everything until step 4. The user can input data in the form, but I the problem is that when I try to generate the table, PHP will show me this error message: "Undefined index: rows on line 70".
As I described earlier I'm just about to learn PHP, so there may be many "not so very nice programming approaches"; therefore I'm open to all kinds of recommendations.
<!DOCTYPE html>
<html>
<body>
<form method="post" target="">
<label for="login">User: </label>
<input name="login">
<br />
<label for="password">Password: </label>
<input name="password" type="password">
<br />
<input type="submit" name="generate" value="Login" />
</form>
<?php
if (isset($_POST['generate'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$hashed_username = sha1($username);
$hashed_password = sha1($password);
$correct_username = '9d6035e25958ec12fca7ec76d68c8daaf4815b9b'; //wims
$correct_password = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'; //test
if ($hashed_username != $correct_username)
die("Wrong user name!");
if ($hashed_password != $correct_password)
die("Wrong password!");
echo "How many rows and columns should the table have? <br />";
echo('
<form method="POST" target="">
Rows: <input type="number" name="rows" min="1" max="100"/><br/>
columns: <input type="number" name="columns" min="2" max="100"/><br/>
<input type="submit" name="generate1" value="Generate Table" />
</form>');
}
if (isset($_POST['generate1'])) {
$rows = $_POST['rows'];
$columns = $_POST['columns'];
global $rows, $columns;
if ($rows > 100 || $rows < 1)
die("Nope!");
if ($columns > 100 || $columns < 2)
die("Nope!");
echo '<form method="POST" target="">';
echo "<table>";
for ($a=1;$a<=$rows;$a++) {
echo "<tr>";
for ($b=0;$b<=$columns;$b++) {
if ($b==0)
echo "<td>$a. Row</td>";
else {
$c = $a . $b;
echo "<td><input type='text' name='$c' /></td>";
}
}
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='generate2' value='Generate' />";
echo "</form>";
}
if (isset($_POST['generate2'])) {
echo "<table>";
for ($a=1;$a<=$GLOBALS['rows'];$a++) {
echo "<tr>";
for ($b=0;$b<=$GLOBALS['columns'];$b++) {
if ($b==0)
echo "<td>$a. row</td>";
else {
$c = $a . $b;
echo "<td>$_POST[$c]</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
?>
</body>
</html>
You need to store your $rows and $columns in $_SESSION variables. With $Globals, I assume you cannot reach to that point, and you get the warning at this point: for ($a=1;$a<=$GLOBALS['rows'];$a++), because $GLOBALS are not declared the second time you reload the page by submitting the second form.
In fact, as W3Schools states, "$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script", while a "session is a way to store information (in variables) to be used across multiple pages." When you submit the pages for the second time, you are in fact refreshing the page, and here Globals are not a pick for you access your rows and columns. Instead you should use sessions to store your $_POST['rows'] and $_POST['columns'].
So, try the following instead. Start Session and then declare new $_Session variables for your $_POST['rows'] and $_POST['columns']. Then voila, the problem is solved.
IMPORTANT: add session_start(); at the top of your page. The very first line.
if (isset($_POST['generate'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$hashed_username = sha1($username);
$hashed_password = sha1($password);
$correct_username = '9d6035e25958ec12fca7ec76d68c8daaf4815b9b'; //wims
$correct_password = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'; //test
if ($hashed_username != $correct_username)
die("Wrong user name!");
if ($hashed_password != $correct_password)
die("Wrong password!");
echo "How many rows and columns should the table have? <br />";
echo('
<form method="POST" target="">
Rows: <input type="number" name="rows" min="1" max="100"/><br/>
columns: <input type="number" name="columns" min="2" max="100"/><br/>
<input type="submit" name="generate1" value="Generate Table" />
</form>');
}
if (isset($_POST['generate1'])) {
$rows = $_POST['rows'] ?? '';
$columns = $_POST['columns'] ?? '';
$_SESSION['rows'] = $rows;
$_SESSION['columns'] = $columns;
global $rows, $columns;
if ($rows > 100 || $rows < 1)
die("Nope!");
if ($columns > 100 || $columns < 2)
die("Nope!");
echo '<form method="POST" target="">';
echo "<table>";
for ($a = 1; $a <= $rows; $a++) {
echo "<tr>";
for ($b = 0; $b <= $columns; $b++) {
if ($b == 0)
echo "<td>$a. Row</td>";
else {
$c = $a . $b;
echo "<td><input type='text' name='$c' /></td>";
}
}
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='generate2' value='Generate' />";
echo "</form>";
}
if (isset($_POST['generate2'])) {
echo "<table>";
$row = $_SESSION['rows'] ?? '';
$columns = $_SESSION['columns'] ?? '';
for ($a = 1; $a <= $row; $a++) {
echo "<tr class='border: 1px solid #BDBDBD'>";
for ($b = 0; $b <= $columns; $b++) {
if ($b == 0)
echo "<td style='border: 1px solid #BDBDBD'>$a. row</td>";
else {
$c = $a . $b;
echo "<td style='border: 1px solid #BDBDBD'>$_POST[$c]</td>";
}
echo "</tr>";
}
echo "</table>";
}
session_destroy();
}
Your code here is the problem
if (!isset($_POST['generate1']))
die('');
Here you are checking if $_POST['generate1] is set, if it is not then die (halt/terminate execution of the script)
php die();
So when you submit your second form (submit has name of generate2) then the above check will fail (it is not set so it will die(); and end execution of your script.
if (isset($_POST['generate1'])) {
// Show the form....
}
Do this for both the generate1 and generate2 and it will only execute that code if the if statements evaluates to true.
instead using "if (!isset($_POST['generate1']))" change it into "if(isset($_POST['generate1']))".When you click generate2 it will be die because that condition is not fulfilled.
<!DOCTYPE html>
<html>
<body>
<form method="post" target="">
<label for="login">User: </label>
<input name="login">
<br />
<label for="password">Password: </label>
<input name="password" type="password">
<br />
<input type="submit" name="generate" value="Login" />
</form>
<?php
if (isset($_POST['generate'])) {
$username = $_POST['login'];
$password = $_POST['password'];
$hashed_username = sha1($username);
$hashed_password = sha1($password);
$correct_username = '9d6035e25958ec12fca7ec76d68c8daaf4815b9b'; //wims
$correct_password = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'; //test
if ($hashed_username != $correct_username)
die("Wrong user name!");
if ($hashed_password != $correct_password)
die("Wrong password!");
echo "How many rows and columns should the table have? <br />";
echo('
<form method="POST" target="">
Rows: <input type="number" name="rows" min="1" max="100"/><br/>
columns: <input type="number" name="columns" min="2" max="100"/><br/>
<input type="submit" name="generate1" value="Generate Table" />
</form>');
}
if (isset($_POST['generate1'])){
$rows = $_POST['rows'];
$columns = $_POST['columns'];
if ($rows > 100 || $rows < 1)
die("Nope!");
if ($columns > 100 || $columns < 2)
die("Nope!");
echo "<form method='POST' target=''>";
echo "<input type='hidden' name='row' value='$rows'/>";
echo "<input type='hidden' name='column' value='$columns'/>";
echo "<table>";
for ($a=1;$a<=$rows;$a++) {
echo "<tr>";
for ($b=0;$b<=$columns;$b++) {
if ($b==0)
echo "<td>$a. Row</td>";
else {
$c = $a . $b;
echo "<td><input type='text' name='$c' /></td>";
}
}
echo "</tr>";
}
echo "</table>";
echo "<input type='submit' name='a' value='Generate' />";
echo "</form>";
}
if (isset($_POST['a'])) {
$rows = $_POST['row'];
$columns = $_POST['column'];
echo "<table border='1'>";
for ($a=1;$a<=$rows;$a++) {
echo "<tr>";
for ($b=0;$b<=$columns;$b++) {
if ($b==0){
echo "<td>$a. row</td>";
}else {
$c = $a . $b;
echo "<td>$_POST[$c]</td>";
}
}
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
First
Your primary need is to READ THE MANUAL for all the things you're doing, thus you will see that the sha1() Manaul page states:
Warning
It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm.
You REALLY should be fixing this issue.
Anyway, your issue is:
Undefined index: rows on line 70
Which (I guess, because you didn't indicate in your question) is this line:
for ($a=1;$a<=$GLOBALS['rows'];$a++) {
This means that $GLOBALS key rows doesn't exist. Why? All PHP data is generated when a script is executed; before ANY script starts, the PHP knows NOTHING, there is never any incoming data at the start if the PHP script.
Some people here might shout and scream "SESSIONS!!" but even the $_SESSION array is empty at the start of the script, until the PHP code has read the stored session data in the cookie key.
So how do you populate $GLOBALS? What you did was not far off, but you ran the form and submitted the data to $_POST['generate1'] which worked, and this populated the data, but this presented a form to the end user so that user then had to resubmit the form, and by default that reloads the page, therefore restarting the PHP script from zero again, so all data in $GLOBALS is forgotten.
How do you make PHP "remember" data when loading a page? In general there are several ways; all of them have positive and negative sides:
Database. Read and write data to a third party
Sessions. Read and write data to a file/database associated with that specific client only.
Form data, reading data from a submitted form or via URL parameters (GET/POST).
Using (3) is probably easiest for you; so when you run the $_POST['generate1'] you need to add hidden inputs to your form so your "part 2" form can then pass on this data to "part3" form ($_POST['generate2']) .
And that's the data you need to read, not the GLOBALS.

Undefined Offset when looking through an array to display values

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>

form checkbox value php

I have a form created by a while loop in php like this :
<form action='#' method='post'>
<input type='hidden' name='form_valid' id='form_valid'>
<?php
$i=-1;
$result_array = array();
//the while is from a simple mysql query
while( $line = $results->fetch() )
{
$i++;
echo"<input type='checkbox' class='checkbox' value='".$line->nid."' id='".$i."'>";
echo $line->title;
echo'<br>';
$result_array[$i] = $line->nid;
}
<input type='submit'>
?>
</form>
Then later on the code I'd like to store the values of the checked checkboxes only in a new array :
if (isset($_REQUEST['form_valid'])) //checking is form is submitted
{
foreach($result_array as $result)
{
if($result == $_REQUEST[$j]) <<<< ERROR
{
$final_array[$j] = $result;
}
}
}
Surprisingly, this code does not work at all.
The error message is "Notice : Undefined offset: 0", then offset 1 then 2 etc ...
The line where the message says theres an error is the marked one.
I really have no idea how to do this. Someone ? =)
Don't try to do it this way, this just makes it hard to process, just use a grouping name array: name="checkboxes[<?php echo $i; ?>]", then on the submission, all values that are checked should simply go to $_POST['checkboxes']. Here's the idea:
<!-- form -->
<form action="" method="POST">
<?php while($line = $results->fetch()): ?>
<input type="checkbox" class="checkbox" name="nid[<?php echo $line->nid; ?>]" value="<?php echo $line->nid; ?>" /><?php echo $line->title; ?><br/>
<?php endwhile; ?>
<input type="submit" name="submit" />
PHP that will process the form:
if(isset($_POST['submit'], $_POST['nid'])) {
$ids = $_POST['nid']; // all the selected ids are in here
// the rest of stuff that you want to do with it
}

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>

HTML/PHP Survey not passing to MySQL database properly

I'm trying to make a small survey that populates the selections for the dropdown menu from a list of names from a database. The survey does this properly. I want to submit the quote the user submits with this name into a quote database. The quote text they enter into the field goes in properly, however, the name selected from the menu does not get passed in. Instead I get a blank name field.
I understand some of my code is out of context, but the name is the only thing that does not get passed in properly.
On form submit, I include the php file that submits this data to the database:
<form action="<?php $name = $_POST['name']; include "formsubmit.php";?>" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<input type="submit" value="Submit!" />
</form>
The variable $name comes from this (which populates my dropdown menu):
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
echo "</select>";
And here is my formsubmit.php:
<?php:
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
header("Location: quotes.php");
if (#mysql_query($sql)) {
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
Your form action stuff looks weird, but regardless, I think the problem you're having has to do with not setting $name = $_POST['name'] like you're doing with $quotetext = $_POST['quotetext']. Do that before the sql statement and it should be good to go.
edit to try to help you further, I'll include what the overall structure of your code should be, and you should tweak it to fit your actual code (whatever you're leaving out, such as setting $query for your name options):
file 1:
<form action="formsubmit.php" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<select name='name'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
?>
</select>
<input type="submit" value="Submit!" />
</form>
formsubmit.php:
<?php
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$name = $_POST['name'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
$nyme = htmlspecialchars($temp['name']);
echo "<option value='$nyme'>$nyme</option>";
}
echo "</select>";-
This way you will receive the value of the name in $_POST array
and you have to get that value out of $_POST array as well you need to change the
code add the following line to get the name in your script.
$name = $_POST['name'];
you need to change the form action tag
<form action='formsubmit.php' .....>
and in that file after successful insertion you can redirect the user to whereever.php.
so it was fun explaining you every thing bit by bit change this now in your code as well.
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}

Categories