PHP While Loop logic - php

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.

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.

If uncheck the check box delete row in my SQL table

Actually I am very new to php.. I have a task that select records from database as checkboxes checked. When I uncheck a checkbox it should delete that particular record from my database..
My code is
<?php
if(isset($_POST['delete']))
{
$test=$_POST['test'];
$qun1=$_POST['question1'];
//DB connection
$CON=mysql_connect("localhost","root","");
mysql_select_db("Dbname");
if($qun1!=0 && $test!=0)
{
foreach($qun1 as $qunestion)
{
echo $question; //this is for testing
$query=mysql_query("delete from test_question where test_questions_id='$test' AND question_id IN ('$question') " ) or die(mysql_error());
}
if($query)
{
echo "success";
}
else
{
echo "No";
}
}
}
?>
my code is working properly but if i use NOT IN in the place of IN it is not working..why?..if unchecked the records it should be delete..i already retrieve records from database as checked fields..
My html markup:
<script>
function fun2(ts)
{
$.post("ajax2.php",{qs:ts},function(data)
{
document.getElementById('div1').innerHTML=data
})
}
</script>
<form action="somepage.php" method="post">
//dynamic selection test code
<select name="test" id="test" onChange="fun2(this.value);">
<option value="">Select Test</option> </select>
<div id="div1" > </div>
<input type="submit" name="delete" value="Delete" >
</from>
my ajax code:
<?php
$qs=$_REQUEST['qs'];
mysql_connect("localhost","root","");
mysql_select_db("advancedge");
$sql=mysql_query("select question_id from test_question where test_questions_id='$qs'");
if($sql)
{
while($rec=mysql_fetch_row($sql))
{
echo "<input type='checkbox' name='question1[]' value='$rec[0]' checked='checked' >";
}
}
?>
If I understand correctly, you want to delete as soon as the item is unchecked? To check if a checkbox is unchecked, you have to use javascript. PHP runs on the server, not the client side (you could use ajax, but I would recommend not to for this).
I would recommend, you delete whatever you want to on form submission, if you don't know how to do that,I can tell you if you post the html part up.
I would also recommend you learn PHP from a course on the internet, so you know some standards and get some good practices. (Youtube or Lynda.com)
It is an old post, but if someone end up here - this might solve the problem:
<?php
echo "<form action='' method='post'>";
echo "<input type='checkbox' id='chk_1' name='chk_1' value='First' />chk 1 </br>";
echo "<input type='checkbox' id='chk_2' name='chk_2' value='Second' />chk 2 </br>";
echo "<input type='submit' />";
echo "</form>";
$check = array();
// Set all checkboxes to 0 if unchecked
for($i = 1; $i<=2; $i++) {
$check["chk_$i"] = isset($_POST["chk_$i"]) ? 1 : 0;
}
// Output of the array
echo '<pre>';
var_export($check);
echo '</pre>';
The code will set all unchecked checkboxes to 0.
Then you have to take care of that using something like this:
<?php
if($_GET['chk_1'] == 0) {
$sql = "DELETE FROM mytable WHERE...";
}

Form: make a loop to save different value of a same field name

I do a form, inside I would like to do a loop for to show the same field. Each field will have different value and I would like to use sessions to take all the value.
Here is my code:
for ($i = 1; $i <= 5; $i++) { //normally not 5 but a random number, choose by user
echo "Numero ";
echo $i;
?>
<input type="text" name="number2" id="number2"/>
<?php
}
?>
</form>
<?php
echo $_POST['number2'];
$my_array=array($_POST['number2']);
$_SESSION['countnumb']=$my_array;
in another page:
foreach($_SESSION['countnumb'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
I can't register any number. How can I do this? thanks
Basics First - ids should be unique in a webpage.
Declaring <input type="text" name="number2" id="number2"/> in a loop is wrong.
For creating multiple input using loop try like this-
echo "<input type='text' name='number[$i]' id='number{$i}' />";
<input type="text" name="number[2]" id="number2"/>
would make $_POST['number'] an array which you can loop though server side, This is described here http://www.php.net/manual/en/faq.html.php#faq.html.arrays
foreach ($_POST['number'] as $number){
echo $number;
}
for example
this would make your code
for ($i = 1; $i <= 5; $i++) { //normally not 5 but a random number, choose by user
echo "<input type="text" name="number[$i]" id="number{$i}"/> ";
?>
<?php
}
?>
</form>
<?php
print_r( $_POST['number'] );
$_SESSION['countnumb']= $_POST['number'];

PHP - Getting back Post from forEach select form

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);
?>

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?

Categories