Hi I'm trying to update a single field from a HTML form, for some reason one of the session variables I am passing to the update query is not being accepted. I have already echoed the variable in the page so am fairly certain it exists in memory.
NB, I know my code is horrifically insecure but I'm learning PHP and once I've got the basics working Ill go over it and bring it upto best practice standards.
E2A: If I do var_dump($filename); before trying to run the query it returns string(6) "356/18", after the query it returns NULL. I'm not unsetting the variable anywhere so where could it be going!
Here is my form:
<form method="post" action="">
<p>Your username is: <?php echo $_SESSION['userid'] ?> Your company ID is: <?php echo $companyid['id']?></p>
<h3>Please enter note for file: <?php echo $filename; ?></h3>
<table width="200" cellpadding="5">
<tr>
<th width="18%" align="right" nowrap>Add Note: </th>
<td width="82%" nowrap>
<input type="text" name="note" />
</td>
</tr>
<tr>
<td colspan="2" width="100%" nowrap>
<input type="submit" value="Submit" name="Submit" />
</td>
</tr>
</table>
</form>
Here is my UPDATE query:
$sql = "UPDATE fields SET Notes = ('".mysql_real_escape_string(stripslashes($_REQUEST['note']))."')
WHERE companyId='".$companyid['id']."' AND fileNumber ='".$filename."'";
if($result = mysql_query($sql)) {
echo "<h1>Thank you</h1>Your information has been entered into our database<br><br>";
echo $sql;
echo $filename;
} else {
echo "ERROR: ".mysql_error();
}
} else {
echoing $sql produces the following:
UPDATE fields SET Notes = ('asdasda') WHERE companyId='11' AND fileNumber =''
and here is the bit where I instantiate the POST vars.
include "header.php";
$checkFiles = "checkFiles.php";
// Catches form input from previous page and stores it into session variable called filename for future reference;
$_SESSION['filename']=$_POST['filename'];
$filename = $_SESSION['filename'];
//User id stuff from previous page too;
$userid = $_SESSION['userid'];
$id = mysql_query("SELECT id FROM users WHERE DXNumber='".$userid."'");
// Returns pointer so fetch it as an array and insert it into variable $companyid for later use;
$companyid = mysql_fetch_array($id);
You need to include session_start() on the top of each file.
Just do:
AND fileNumber ='".$_SESSION[filename]."'";
In your update query.
If that doesn't work, make sure that a value for $_SESSION[filename] is being set.
<h3>Please enter note for file: <?php echo $filename; ?></h3>
Create a input box
<input type="text" name="filename" value="<?php echo $filename; ?>"/>
Then filename value will be pass to $_POST array
Related
Here's my case (relatively new on php): I got a page "zoek_form.php" where you can enter 2 search values in a form (naam and categorie). When submitted, page "zoek.php" is loaded and a search will be performed (mysql 5.6). To perform the search the 2 values are obtained from the 2 session variables. So far so good, the search works and the rows are retrieved.
But now I want the user to be able to make a sequence (via ORDER BY) in zoek.php, based on a dropdown list. The selected value will be stored in a 3rd session variable. But now the problem: when selecting a sequence and submit the form, the first 2 session values are lost. I'm puzzled why. The essence of session variables is just storing the values and to be able to use them over and over again? (till they are overwritten or killed).
Of course I use session_start(); at the beginning of the php-script (otherwise it would not have worked at all ;-). Any ideas?
Here's zoek_form.php:
<html>
<head>
<title>Zoeken</title>
</head>
<body>
<?php session_start(); ?>
<form name="form1" method="POST" action="zoek.php">
<table border="0">
<tr><td>Naam product:</td>
<td><input type="text" size="50" name="form_naam"></td></tr>
<tr><td>Categorie:</td>
<td><input type="text" size="50" name="form_cat"></td></tr>
<tr><td></td>
<td align = "right"><input type="submit" name="B1" value="Zoeken">
</td></tr>
</table>
</form>
</body>
</html>
Here's zoek.php:
<html>
<head>
<title>Zoeken</title>
</head>
<body>
<form name="form1" method="POST" action="">
<table border="0">
<tr><td>Sorteer op:</td>
<td><select name="form_sort">
<option value="Naam">Naam</option>
<option value="Categorie">Categorie</option>
</select></td>
<td><input type="submit" name="B1" value="Sorteer"></td></tr>
</table>
</form>
<?php
session_start();
require_once 'test_connect.php';
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
$_SESSION['form_sort'] = $_POST['form_sort'];
// The 3 lines below were used to check whether session vars were set
// echo $_SESSION['form_naam'];
// echo $_SESSION['form_cat'];
// echo $_SESSION['form_sort'];
function sorteren() {
global $sorteer;
$sorteer = $_SESSION['form_sort'];
if ($sorteer == "Naam") {
$sorteer = "ORDER BY naam";
}
else {
$sorteer = "ORDER BY categorie";
}
}
// Put values from zoek_form.php in vars.
$naam = $_SESSION['form_naam'];
$cat = $_SESSION['form_cat'];
// Check if user has set a sequence. If yes: call function sorteren(),
// if no: leave var $sorteer empty.
if (isset($_SESSION['form_sort'])) {
sorteren();
}
else {
$sorteer = "";
}
// Get rows from table product
$sql = "SELECT * FROM product WHERE naam LIKE '$naam%' OR categorie
LIKE '$cat%' $sorteer";
$result = $conn -> query($sql);
if ($result->num_rows > 0) {
// here code to retrieve rows etc.
}
// Give result free
$result -> free();
// Close connection
$conn -> close();
?>
</body>
</html>
Your form in zoek.php doesn't contain form_naam and form_cat so when you run
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
It sets those values to null. If you want to retain those values you could try passing them back again in the form with hidden input fields
<input type="hidden" name="form_naam" value="<?= $_SESSION['form_naam'] ?>">
<input type="hidden" name="form_cat" value="<?= $_SESSION['form_cat'] ?>">
Another way to prevent overwriting the session values is to only change them if the $_POST values are set
if(isset($_POST['form_naam']) && isset($_POST['form_cat'])) {
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
}
Sorry I'm a bit of a noob when it comes to PHP but I just wondered if someone had an idea on how I could solve this PHP/SQL problem.
I have a PDO statement that gets all users from a database.
With the array of users from the database I create a foreach loop to display all of the users in a table which I want to use to select a specific user, enter a number in the row of the user I select, then click submit and store the users name and also the number. I will use this information to populate another database later.
My question is, I cant seem to reference the user or the number in the table to extract the user and number I enter. When I try and request the numbered entered in the index.php, it will only ever display a number if I enter a number for a the final user in the table. When I try and view the FullName it never works and I get 'Undefined index: FullName' error.
I also specified to 'POST in the form but it doesnt seem to be doing that.
Does anyone have any ideas?
Thanks
//function.php
function getName($tableName, $conn)
{
try {
$result = $conn->query("SELECT * FROM $tableName");
return ( $result->rowCount() > 0)
? $result
: false;
} catch(Exception $e) {
return false;
}
}
//form.php
<form action "index.php" method "POST" name='form1'>
<table border="1" style="width:600px">
<tr>
<th>Name</th>
<th>Number Entered</th>
<tr/>
<tr>
<?php foreach($users as $user) : ?>
<td width="30%" name="FullName">
<?php echo $user['FullName']; ?>
</td>
<td width="30%">
<input type="int" name="NumberedEntered">
</td>
</tr>
<?php endforeach; ?>
</table>
<input type="submit" value="submit"></td>
</form>
//index.php
$users = getName('users', $conn);
if ( $_REQUEST['NumberedEntered']) {
echo $_REQUEST['NumberedEntered'];
echo $_REQUEST['FullName'];
}
The variable FullName isn't transmitted by your form to index.php. Only values of form elemnts are sent. You can add a hidden form field, that contains FullName like this:
<input type="hidden" name="FullName" value="<?php echo $user['FullName']">
But your second problem is, that your foreach loop will create several input fields with the exact same name. You won't be able to recieve any of the entered numbers, except the last one. have a look at this question for possible solutions.
Update
Putting each row in individual form tags should solve your problem:
<?php foreach($users as $user) : ?>
<form action="index.php" method="POST">
<tr>
<td align="center" width="40%" >
<?php echo $user['FullName']; ?>
<input type="hidden" name="FullName" value="<?php echo $user['FullName']; ?>" />
</td>
<td width="30%">
<input name="NumberedEntered"/>
</td>
<td>
<input type="submit" value="submit"/>
</td>
</tr>
</form>
<?php endforeach; ?>
I need som help - I really cant see where I do the mistake!
I need to below code to remember the variable for loading the next page. The page loads using a link like:
editgallery.php?folder=big_fish&id=459
Now I want the below codes to remember the folder variable: big_fish for generating the next link. In the bottom of the codes I use a "location" to load the next page. It looks like:
header("Location: galleries.php?folder".$folder." ");
It should send the user back to the page they came from when clicking "update" in the form in the below codes:
if(!$_POST["submit"])
{
include "header.php";
$query = mysql_query("select name, type, folder, description , displaydate from galleries where id = '".$_GET["id"]."' ");
$row = mysql_fetch_row($query);
$name = $row[0];
$type = $row[1];
$folder = $row[2];
$description = $row[3];
$displaydate = $row[4];
?>
<form method="POST" action="<?=$_SERVER["PHP_SELF"]?>" name="myform" id="myform">
<center><table width="<?=$setting["tablewidth"]?>" class="admintable" cellpadding="<?=$setting["cellpadding"]?>">
<tr>
<td class="adminheader" colspan="2"> <b>Edit Gallery:</b></td>
</tr>
<tr>
<td class="admincell"> Name:</td>
<td class="admincell">
<input type="text" name="name" value="<?=$name?>" size="40"></td>
</tr>
<tr>
<td class="admincell"> Category:</td><td class="admincell">
<?=$folder?>
</td>
</tr>
<tr valign="top">
<td class="admincell"> Display Date:</td>
<td class="admincell" align="">
<input style="border-style:hidden" type="text" value="<?=$displaydate?>" id="from" id="<?php echo $_REQUEST["from"]; ?>" name="displaydate" size="40">
(yyyymmdd - Like <?=date('Ymd');?> or <?=date('Y-m-d');?>)</td>
</tr>
<tr valign="top">
<td class="admincell"> Description: </td><td class="admincell">
<textarea id="Enter you description of the photo set here" name="description"><?=$description?></textarea></td>
<!-- http://ckeditor.com/ -->
<script>
CKEDITOR.replace( 'description' );
</script>
</tr>
<tr>
<td class="admincell" colspan="2"><input type="hidden" name="id" value="<?=$_GET["id"]?>"><center>
<input type="submit" name="submit" value="Update"></center></td>
</tr>
</table></center>
</form><center>
<p>
</table></center>
<?
include "footer.php";
}
else
{
mysql_query("update galleries set name = '".$_POST["name"]."', description = '".$_POST["description"]."' , displaydate = '" . $_POST["displaydate"] . "' where id = '".$_POST["id"]."' ");
header("Location: galleries.php?folder".$folder." ");
//header("Location: galleries.php");
}
Can anyone see why the $folder name from the link is not saved for the location link - why cant the codes "transfer" it from the editgallery.php?folder=big_fish&id=459 link and to the location like: ("Location: galleries.php?folder".$folder." ");
Please advice.
You're missing an equals sign:
header("Location: galleries.php?folder".$folder." ");
should be
header("Location: galleries.php?folder=".$folder." ");
You might want to consider using http_build_query to handle building the URL.
You are vulnerable to SQL injection attacks, and have typos:
header("Location: galleries.php?folder=".$folder." ");
^---missing
Essentially you're generating a link that looks like
galleries.php?folderfoo
instead of
galleries.php?folder=foo
Apart from the missing =, I don't see how you are setting your variable (or database connection...).
You probably want something like:
header("Location: galleries.php?folder=" . $_GET['folder']);
You should also switch to PDO or mysqli and prepared statements as the mysql_* functions are deprecated and you have an sql injection problem.
Edit: Note that when a POST request is made / $_POST["submit"] is set, only the last two lines of the script are executed:
A mysql query without a database connection
A header() call with an undefined $folder variable.
I'm just going to re-write my answer here.
Your code could use some cleanup. Here are some items that I would fix:
<input style="border-style:hidden"
type="text"
value="<?=$displaydate?>"
id="from"
id="<?php echo $_REQUEST["from"]; ?>"
name="displaydate"
size="40">
You have two id's there. No bueno.
<textarea id="Enter you description of the photo set here" name="description"><?=$description?></textarea>
Not really a good idea to have your ID contain spaces. Did you mean to use the title attribute?
<input type="hidden" name="id" value="<?=$_GET["id"]?>">
This is good. And I think this is where your main problem lies. You need to add another hidden input with folder
<input type="hidden" name="folder" value="<?=$_GET["folder"]?>">
This way, when the form is posted, the folder will be sent in the form of $_POST['folder'].
Then, here:
header("Location: galleries.php?folder".$folder." ");
Should become:
header("Location: galleries.php?folder=".$_POST['folder']);
Try that and let us know what happens please.
I have gotten the id numbers of users from my database, and I want to make a button for each user. My code makes a table that shows all the IDs and creates a button for each one. I'm having trouble figuring out how to get the name of those buttons for use in other code. The error I am getting is "undefined variable" (in the 3rd line), which I am most likely getting because I am going at getting the button names wrong.
Basically, the $_POST in the third line is wrong (among perhaps other things). My question is how would one get the name (or id?) of the buttons I have made: how should I fix the $_POST or should I use something else entirely?
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST[$n])) header("location:" . $n . ".php");
}
?>
<div id="mod_user">
<table id='mod_table'>
<th class='ttop'>#</th>
<th class='ttop'>Page</th>
<?php
$result = $db->prepare("SELECT * FROM User");
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$n=$row["UserID"];
?>
<form action="" method="post">
<tr>
<td class='tben'><?php echo $n; ?></td>
<td class='tben'><button type='submit' name=<?php echo $n; ?> >Go here</button></td>
<br />
</tr>
</form>
<?php
} ?>
</table>
</div>
You can try like this:
<td class='tben'><button type='submit' name="usernames[<?php echo $n ?>]" >Go here</button></td>
So you can get button name from $_POST["usernames"] array as below
foreach($_POST["usernames"] as $username => $btn_value)
echo "$username => $btn_name";
My issue is I have a PHP $_POST that returns a null or empty value, and I personally do not see any error with my code (but I know its there) and I can't really step away from it for a few hours since I am on a time schedule. So, I was hoping someone could help me out ;)
Here is what I have, basically:
<table border="0" align="center">
<tr>
<td>
<div id="lvl3">Project Name:</div>
</td>
<td>
<input type="text" name="prjname" maxlength="250">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" name="prjsubmitname">
<input type="button" value="Cancel" onclick="$('#popupoverlay').hide(); $('#prjpopupbox').hide(); $('#prjname').hide(); $('#prjdescription').hide(); $('#prjversion').hide(); $('#prjrelease').hide();">
</td>
</tr>
This is my table for editing a project name- what is important here is the textbox input, I think.
Next I have my PHP:
//Did the user change the Project Name
if (isset($_POST['prjsubmitname']))
{
//Is the input empty
if (!trim($_POST['prjname']))
{
//Input is empty
echo('<script>senderror("Please enter a valid Project Name empty");</script>');
} else {
//Input isnt empty, assign variables
$url = geturlext();
$prjname = mysql_real_escape_string(trim($_POST['prjname']));
//Is input invalid
if (strcasecmp($prjname, "main") == 0 | $prjname == "404")
{
//Input is invalid
echo('<script>senderror("Please enter a valid Project Name invalid");</script>');
} else {
//Input is valid, connect to database
dbconnect();
$checkquery = mysql_query("SELECT * FROM projects WHERE name = '$prjname'") or die(mysql_error());
$check = mysql_num_rows($checkquery);
//Does Project Name already exist
if ($check == 0)
{
//No it does not
$updatequery = mysql_query("UPDATE projects SET name = '$prjname' WHERE name = '$url'") or die(mysql_error());
echo("<script>location.href='index.php?page=" . $prjname . "'</script>");
} else {
//Yes it does
echo('<script>senderror("That Project Name already exists");</script>');
}
}
}
}
This is where I get my issue; No matter what I enter in the textbox, I always get the error message for 'Input is empty'. I have printed the output of $_POST['prjname'] and it is indeed empty.
Now the weird part is, I have this exact same (at least I think) setup for changing the project description, and it works flawlessly. For the sake of comparison- i've included the same parts of the project description editor below.
The table:
<table border="0" align="center">
<tr>
<td>
<div id="lvl3">Project Description:</div>
</td>
<td>
<textarea type="text" name="prjdescription" maxlength="750" style="width:300px; height:100px; resize:none;"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" name="prjsubmitdescription">
<input type="button" value="Cancel" onclick="$('#popupoverlay').hide(); $('#prjpopupbox').hide(); $('#prjname').hide(); $('#prjdescription').hide(); $('#prjversion').hide(); $('#prjrelease').hide();">
</td>
</tr>
And the PHP:
//Did the user change the Project Description
if (isset($_POST['prjsubmitdescription']))
{
//Is the input empty
if (!trim($_POST['prjdescription']))
{
//Input is empty
echo('<script>senderror("Please enter a valid Project Description");</script>');
} else {
//Input isnt empty, do stuff
$url = geturlext();
$prjdescription = mysql_real_escape_string(trim($_POST['prjdescription']));
//Connect and change description
dbconnect();
$updatequery = mysql_query("UPDATE projects SET description = '$prjdescription' WHERE name = '$url'") or die(mysql_error());
echo("<script>location.href='index.php?page=" . $url . "'</script>");
}
}
For clarification, both tables are in the same form tag, and the PHP is right next to eachother.
No errors on Firebug, matter of fact Firebug doesn't give me anything. Other than that, I'm sure it's some really small typo that I am overlooking.
I have found a solution to this issue:
Renaming the variable '$prjname' in the Project Name editing PHP fixes the issue.
It would seem that having a variable ($prjname) with the same name as a $_POST (['prjname']) returns an empty or null string. No idea why.
Thanks to those who tried to help
EDIT: Actually, I get the error again if I only change the variable name ($prjname)- It only fixes when I change the $_POST name... Odd.
Looking at the description of above issue, we can conclude that form elements must be encapsulated within form tag ,then only form data will be posted to server.
So as a solution to your problem, you need to define input elements within form tag.