PHP not properly inserting into the database - php

I'm converting my code from extremely long GET statements (is that the correct word?) into separate files for each page. The code I'm about to show worked fine before I moved it to it's own file.
The page's full code is:
<?
require_once('./inc/glob_head.php');
$database->openConnection();
$listOfGamesQuery = $database->queryDB("SELECT * FROM mainSite_games");
if (isset($_GET) && $_GET['action'] == 'deleteGame')
{
$gameID = $_GET['gameID'];
$database->queryDB("DELETE FROM mainSite_games WHERE id='$gameID'");
redir('viewGames.php');
}
elseif (isset($_GET) && $_GET['action'] == 'editGame')
{
$gameID = $_GET['gameID'];
$gameNameQry = $database->queryDB("SELECT gameName FROM mainSite_games WHERE id='$gameID'");
while ($gameNameDta = $database->fetchArray($gameNameQry))
{
$gameName = $gameNameDta['gameName'];
}
$gameDescQry = $database->queryDB("SELECT gameDesc FROM mainSite_games WHERE id='$gameID'");
while ($gameDescDta = $database->fetchArray($gameDescQry))
{
$gameDesc = $gameDescDta['gameDesc'];
}
?>
<form name="editGame" id="editGame" action="viewGames.php?action=processEdit&gameID=<? echo $gameID; ?>" method="POST">
<input type="text" name="gameName" value="<? echo stripslashes($gameName); ?>" /><br />
<textarea name="gameDesc" class="span12" rows="10"><? echo stripslashes($gameDesc); ?></textarea><br />
<input type="submit" name="submitEditGame" class="btn btn-primary" />
</form>
<?
}
elseif (isset($_GET) && $_GET['action'] == 'processEdit')
{
$gameID = $_GET['gameID'];
$gameName = $database->escapeString($_POST['gameName']);
$gameDesc = $database->escapeString($_POST['gameDesc']);
$database->queryDB("UPDATE mainSite_games SET gameName='$gameName' WHERE id='$gameID'");
$database->queryDB("UPDATE mainSite_games SET gameDesc='$gameDesc' WHERE id='$gameID'");
redir('viewGames.php');
} else {
echo '<div class="contCont">';
echo '<table>';
echo '<thead>';
echo '<tr>';
echo '<th>Game Name</th>';
echo '<th>Delete</th>';
echo '<th>Edit</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($listOfGames = $database->fetchAssoc($listOfGamesQuery)) {
echo '<tr>';
print '<td>' . stripslashes($listOfGames['gameName']) . '</td>';
print '<td>Delete</td>';
print '<td>Edit</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</body>';
echo '</html>';
}
$database->closeConnection();
?>
glob_head just provides the database class, the database connection, the functions file requirement, and styling/page structure that is constant around the site. Having stated this, the $database calls are not mistakes, and are actually defined elsewhere.
Now the problem is, in the above code, the editGame elseif block pulls information from the database successfully, therefore I assume that it must be getting the information correctly. Now, when a user clicks submit, it'll take them to the next block, processEdit, and that for some reason makes the fields blank and sets the blank values in the database. I have no idea what's going on. Maybe this needs a fresh set of eyes? Thanks in advance.
For your reference, the 'redir' calls are a custom function that uses javascript redirection instead of relying on headers. I find it cleaner, and possibly easier to use than changing the structure of the code.

You are submitting METHOD="POST" but looking at the $_GET superglobal variable. The $_GET variable is empty, because there is no GET submission being made.
Change all instances of $_GET to $_REQUEST (or $_POST), or change METHOD="POST" to "METHOD="GET".

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.

HTML form in while loop, how to transfer data from each item?

I have tried to solve it and look around but not even sure what I should be searching for.
I have made a product grid through a while loop, in the loop with each product and input-tag has been used for users to mark how many items of each product is wanted.
The product grid
However I have trouble distinguishing the value of each input field and what "name" it should be stored under to be able to retrieve it when running the second script of processing the order? I also need to be able to connect an id with each value.
The code for the grid:
I know I need to make a unique name in the input name, however how and which makes sense?
<div id="content">
<h1>Products</h1>
<form action="processorder.php" method="post">
<table align="center">
<?php
$db = include "connect2db.php";
mysqli_set_charset($db,"utf8");
$query = 'SELECT * FROM products_josie';
$result = $db->query($query);
$count = 0;
while($res=$result->fetch_assoc())
{
if($count==3)
{
echo '</tr>';
$count = 0;
}
if($count==0)
echo '<tr>';
echo '<td>';
?>
<a href="productsdetails.php?clickedid=<?php echo $res['product_id']?>">
<img src="products/<?php echo $res['photo']; ?>" width="200" height="150"/>
</a>
<br/>
<?php
echo '<p>';
echo $res['product_name'];
echo '</br>';
echo 'DKK ';
echo $res['price'];
echo '</p>';
echo '<p>';
echo '<input type="number" name="amount" min="0"';
echo '</p>';
$count++;
print '</td>';
}
if($count>0)
print '</tr>';
?>
</table>
<input type="submit" value="Submit Order">
</form>
</div>
I think what you are looking for is how to get the amounts for different products. If so, something like this might do it:
$prod = $res['product_name'];
echo '<input type="number" name="amount[$prod]" min="0"';

PHP $_GET to same page from form submit

I am trying to use the $_GET value to load on the same page as my form instead of opening a new page. For example, the form is on my page "products.php" and I want the form to filter database results by type of product. So on submit, it should redirect to "products.php?type=tee".
If I manually type it in the address bar it works like a charm, but I can't get the form submit to load it.
Here's my code (Update: Here's the whole file, using require_once into a basic html5 template):
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Populate Items to Show
function populateItems($result){
while ($row = $result->fetch_assoc()){
if ($row['available']){
echo '<li><img src="', $row['image'], '" />';
echo '<ul>';
echo '<li><h1>', $row['product'], '</h1></li>';
echo '<li><h2>', $row['description'], '</h2></li>';
echo '<li><h3>$', $row['price'], '</h3></li>';
echo '</ul>';
echo '</li>';
}
}
$result->free();
}
//Create Item List
echo '<ul class="item">';
//Create Filter
echo '<li id="filter">';
if ($result = $conn->query("SELECT DISTINCT type FROM products")){
echo 'Filter Results By: <form method="GET" action="', $_SERVER['PHP_SELF'], '">';
echo '<select>';
echo '<option>Show All</option>';
while ($type = $result->fetch_assoc()){
echo '<option name="type" value="', $type['type'], '">', $type['type'], 's</option>';
}
echo '</select>';
echo '<input type="submit" value="Go" />';
echo '</form>';
}
echo '</li>';
//Find if Filter Exists
if (isset($_GET['type']) && $_GET['type'] != "" ){
$gettype = $_GET['type'];
$filtertype = $conn->query("SELECT * FROM products WHERE type='$gettype'");
$count = $filtertype->num_rows;
if ($count <= 0){
populateItems($conn->query("SELECT * FROM products"));
}else{
populateItems($conn->query("SELECT * FROM products WHERE type='$gettype'"));
}
}else{
populateItems($conn->query("SELECT * FROM products"));
}
//End Item List
echo '</ul>';
?>
I've searched all over and haven't found anything that quite answers my question... Any help would be appreciated!
You have your <option name="type" named when it should be the <select>.
<option> does not have named attributes.
Therefore, you need to remove name="type" from your <option> and change your <select> to <select name="type">
Change
<form method="post" action="">
To
<form method="get" action="">
You have to change the Method if you want to use GET! Like this:
...<form method="get" action="">...

more than 1 form at one page

I've problem with multiple form at one page. At page index I include 4 forms
include('./poll_1a.php');
include('./poll_2a.php');
include('./poll_3a.php');
include('./poll_4a.php');
The form code at every poll page is the same. I include some unique markers ($poll_code) for every scripts but the effect is when I use one form - the sending variable are received in the others. But I would like to work each form individually.
The variable $poll_code is unique for every script -> 1 for poll_1, 2 for poll_2 etc.
The same situation is with $cookie_name
$cookie_name = "poll_cookie_".$poll_code;
than, as I see, cookies have different names.
$poll_code = "1"; // or 2, 3, 4
?>
<p>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" name="<?php echo $poll_code; ?>">
<input type="hidden" name="poll_cookie_<?php echo $poll_code; ?>" value="<?php echo $poll_code; ?>">
<table>
<?php
//print possible answers
for($i=0;$i<count($answers);$i++){
?><tr><td style="\text-allign: left;\"><input type="radio" name="vote_<?php echo $poll_code; ?>" value="<?php echo $i; ?>"> <?php echo $answers[$i]; ?></td></tr><?php
}
echo "</table>";
echo "<br>";
if ($_COOKIE["$cookie_name"] == $poll_code ) {
echo "<br> nie można głosować ponownie ...";
} else {
?>
<p><input type="submit" name="submit_<?php echo $poll_code; ?>" value="głosuj !" onClick="this.disabled = 'true';"></p>
<?php
}
?>
</form>
</p>
Q: how to make this forms to work individually at one page?
//------------------- EDIT
the receiving part of the script
$votes = file($file);
$total = 0;
$totale = 0;
$poll_cookie = 0;
if (isset($_POST["vote_$poll_code"]) && isset($_POST["poll_cookie_$poll_code"])) {
$vote = $_POST["vote_$poll_code"];
$poll_cookie = $_POST["poll_cookie_$poll_code"];
}
//submit vote
if(isset($vote)){
$votes[$vote] = $votes[$vote]+1;
}
//write votes
$handle = fopen($file,"w");
foreach($votes as $v){
$total += $v;
fputs($handle,chop($v)."\n");
}
fclose($handle);
Of course, the $file have the unique declaration too (at top of the script, under the $poll_code declaration).
$file = "poll_".$poll_code.".txt";
I think the issue might be that <?php echo $poll_code; ?> is outside the loop so maybe that it's always using the same value assigned to it, maybe put it inside the loop

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