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.
Related
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
}
Can you Help me?? I am trying for some validation in my system, but I got stuck up on my ideas.
I created a text box that will looped when you enter any number. When the text box appear the user will have to fill up names, but if the user accidentally type a duplicated name the prompt message will appear saying: "Errors".
There is minor bug in my system and I want to fix it. I have think a lot of methods but this is the best fit to my system.
Here is the code:
<form action="fq1.php" method="post">
<input type="text" name="num" id="num">
<input type="submit" value="select" name="select" id="select" />
<?php include 'conectthis.php';
$num = $_POST['num'];
if(isset($_POST['select']))
{
$x = 0;
while($x <= $num)
{
$x++;
echo "<input type='text' name='txt".$x."' />";
}
echo "<input type='submit' name='save' id='save' value='Save'>";
}
if(isset($_POST['save']))
{
$y = 0;
while($y<=$num)
{
$y++;
$mypost1 = "txt". $y;
if($_POST[$mypost1] == $_POST[$mypost1])
{
$prompts = "<script>alert('Names was not saved, please ensure that there are no duplicated Names');</script>";
}
else
{
$runthis = "Update sampletable SET samplename = '$_POST[$mypost1]' WHERE id = '$y'";
mysql_query($runthis) or die(mysql_error());
}
}
echo $prompts;
}
?>
</form>
Now my problem is if($_POST[$mypost1] == $_POST[$mypost1]) the textbox will recognize it self and show the prompt message even there is no duplicated name(s).
It's a scratch from my code I think I know it is right.
Thank you in advance, I am new to this and still studying.
i have a website where the admin can choose to add a certain number of bbcode tags and the corresponding html tags.
First he chooses how many tags he wants to add from a drop down select form in a for Each loop.
Depending on how many tags he chose when he clicked the submit button, the corresponding number of input tags appear in a second form, also in a for Each loop. He fills in the bbcode and html input and clicks the submit button. Normally the tags should be added to my database but in this case when he clicks submit the form disappears and nothing is added..
Here is the code :
//FIRST FORM WHERE HE DECIDES HOW MANY TAGS TO ADD
<form id='nbbalises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>How many tags ?</legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
echo '<select name="number">';
$range = range(1,50,1);
foreach ($range as $nb) {
echo "<option value='$nb'>$nb</option>";
}
echo "</select>";
?>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form><br /> <br />
<?php
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
//SECOND FORM WHERE I GENERATE THE INPUT DEPENDING ON THE NUMBER CHOSEN FROM FIRST FORM
<form id='balises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>Balises bbc : </legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
foreach ($range2 as $nb2) {
echo "<label>bbcode tag $nb2 :</label>
<input type='text' size='40' name='bbc$nb2' id='bbc$nb2' maxlength='40' />
<label>html tag $nb2 :</label>
<input type='text' size='40' name='html$nb2' id='html$nb2' maxlength='40' />
<br />";
}
}
?>
<input type='submit' name='Submit2' value='Submit2' />
</fieldset>
</form>
<?php
//PROBLEM STARTS HERE, NOTHING WORKS UNDER HERE
if (isset($_POST['Submit2'])){
//CONNECT TO MY DATABASE
connectDB();
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
}
mysql_close();
}
}
//MY FUNCTIONS TO ADD THE BBCODE AND HTML TO DATABASE
function connectDB(){
//connexion DB
$link = mysql_connect('127.0.0.1', 'USERNAME', 'PASSWORD');
if (!$link) {
die('Erreur de connexion: ' . mysql_error());
}
$db = mysql_select_db('1213he200967',$link) or die("N'a pu selectionner
1213he200967");
mysql_query("SET NAMES 'utf8'");
}
function addBbc($bbc, $html){
$b = mysql_real_escape_string($bbc);
$h = mysql_real_escape_string($html);
$query="INSERT INTO bbcode (BBC,HTML) VALUES ('$b','$h')";
$result = mysql_query($query) or die("error");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
return false;
}
else return true;
}
Thank you very much, and sorry if my code is amateur-ish, i'm only starting in php.
EDIT
Found part of my problem
$number = $_POST['number'];
$range2 = range(1,$number,1);
This goes from 1 to the number chosen by the user in the first form.
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
This goes from 0 to $number - 1
So i changed my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
if (!(empty($_POST["bbc$nb"])) && (empty($_POST["html$nb"]))) {
addBbc($_POST["bbc$nb"], $_POST["html$nb"]);
}
else echo "$nb tags empty ";
This works a bit better but now it goes to the else just here above and displays "2 tags empty", so it still doesn't quite work.
Ok to solve it I finally decided to post the data from the second form to another page and i modified my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
$varBbc = 'bbc'.$nb;
$varHtml = 'html'.$nb;
if ((isset($_POST[$varBbc])) && (isset($_POST[$varHtml]))) {
addBbc($varBbc, $varHtml);
}
else echo "$nb tags empty ";
}
Apparently using !empty instead of isset doesn't work in this case, maybe because of the html tags.
$nb should be in double quotes.
so echo "<option value='$nb'>$nb</option>"
change to echo "<option value='".$nb."'>$nb</option>";
and also
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
change to:
if (isset($_POST['submit'])) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
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?
I create one form when i enter number of Rows & Columns then that number of rows & Column table would be generated i want save values entered into that table into database.Please anyone can help me..
My PHP CODE:
<?php
global $Hostname;
global $Username;
global $Password;
global $Database_name;
function getConnection()
{
$Hostname = "localhost";
$Username ="root";
$Password ="";
$Database_name="labdata";
$oMysqli = new mysqli($Hostname,$Username,$Password,$Database_name);
return($oMysqli);
}
if(isset($_POST['submit']))
{
echo "<table border='1' align='center'>";
for($iii = 0;$iii <$_POST['column'];$iii++)
{
echo "<tr>".$jjj."</tr>";
for($jjj = 0; $jjj <$_POST['rows'];$jjj++) //loop for display no. of rows.
{
echo "<td>" ."<input type=\"text\" name='$iii'>"."</td>";
}
}
echo "</table>";
echo"<form name=\"aa\" method=\"post\">";
echo "<input type=\"submit\" name=\"save\" value=\"save\">";
echo "</form>";
}
$TestName = $_POST['testname'];
$Result = $_POST['result'];
$Unit = $_POST['unit'];
$NormalRange = $_POST['NormalRange'];
if(isset($_POST['save']))
{
$InsertQuery = "INSERT INTO rct(testname,result,unit,NormalRange) VALUES('$TestName','$Result','$Unit','$NormalRange')";
$oMysqli= getConnection();
$oMysqli->query($InsertQuery);
print_r($InsertQuery);exit();
while($Row = $InsertQuery->fetch_array())
{
$TestName = $Row['testname'];
$Result = $Row['result'];
$Unit = $Row['unit'];
$NormalRange = $Row['NormalRange'];
}
}
?>
<html>
<head>
<title>Rct</title>
</head>
<body>
<form name='abc' method="post">
<label for='Table'>Define Table</label>
<label for='rows'>Row</label>
<input type="text" name="column"></input>
<label for='column'>Column</label>
<input type="text" name="rows"></input>
<input type="submit" name="submit" value="submit" onclick="aaa()">
</form>
</body>
</html>
There are many problems with your code:
The table containing <input/>s should be inside <form name='aa'>.
The inputs that are in the table should be named something like $iii[].
The [] tells PHP to create an array of all the rows in $_POST, so you can access $_POST[0][0] for row 0, col 0, $_POST[1][2] for row 2, col 1, etc.
You seem to have rows and columns backwards.
All your <input/> tags are missing the /.
There's no form with inputs named testname, result, unit, NormalRange, so why are you accessing these $_POST values?
fetch_array() can only be used after a SELECT query. INSERT doesn't return any values.
Probably other things I missed.
First of all you must correct the input tag
Replace
<input type="text" name="column"></input>
To
<input type="text" name="column" />
Second the upper loop must be row loop instead of colum as column sit inside the row
if(isset($_POST['submit']))
{
echo"<form name=\"aa\" method=\"post\">";
echo "<table border='1' align='center'>";
for($iii = 0;$iii <$_POST['rows'];$iii++)
{
echo "<tr>";//start Row here
for($jjj = 0; $jjj <$_POST['column'];$jjj++) //loop for display no. of rows.
{
echo "<td>" ."<input type=\"text\" name='".$iii.$jjj."'>"."</td>";//all TDs must be inside the row
}
echo "</tr>";//end row here
}
echo "</table>";
echo "<input type=\"submit\" name=\"save\" value=\"save\">";
echo "</form>";
}
And of course table must be inside the form.
Let me know if this helps