Variable is not usind in link? - php

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.

Related

PHP $_GET and $_POST variables are not working properly

I have an error in my code that may seem ridiculously simple to figure out, but I've looked at it for hours and haven't yet been able to determine the problem.
To edit a database record, I use the following link to pass the record id to the edit page:
Edit
...and here is the edit_short.php file:
$title = "";
$short_text = "";
$id = 0;
if (isset($_GET['id'])) {
$id=$_GET['id'];
$short = (object)Short::find_by_id($id);
$title = $short->title; // My problem is the scope of $title and $short_text
$short_text = $short->short_text; // Is limited within this if statement
}
if (isset($_POST['edit_short_btn'])) {
echo $title."<br/>";
echo $short_text."<br/>";
}
This is the form that is submitted:
<form method="POST" action="edit_short.php" id="post_form">
<table>
<tr>
<td><input type="text" name="title" value="<?php echo $title; ?>" class="textField" placeholder="Title of short"></td>
</tr>
<tr>
<td><textarea name="short_text" id="short_text" placeholder="Short text"><?php echo $short_text; ?></textarea></td>
</tr>
<tr>
<td><input type="submit" name="edit_short_btn" value="Update short"></td>
</tr>
</table>
</form>
I am able to verify that the submitted id is set using $_GET['id'] and I can pass its value to $id in edit_short.php, but when I get the record and set the $title and $short_text variables, I am unable to access them in the if (isset($_POST['edit_short_btn'])) statement.
How do I check that both the $_GET['id'] and the $_POST['edit_short_btn'] are set and still be able to display the $title and $short_text?
Based on your code, you'll never have both the $_GET case and $_POST case at the same time. You'll hit the $_GET case after clicking the link (the page URL will include the ?id=... query string), and the $_POST case after submitting the form (no query string).
The GET is only sent with the link click. Your form is sending a POST so all the data points you want should be in the form. You can have hidden values in the form using the hidden input type. So you should be able to use:
<form method="POST" action="edit_short.php" id="post_form">
<input type="hidden" value="<?php echo intval($_GET['id']);?>" name="id" />
<table>
<tr>
<td><input type="text" name="title" value="<?php echo $title; ?>" class="textField" placeholder="Title of short"></td>
</tr>
<tr>
<td><textarea name="short_text" id="short_text" placeholder="Short text"><?php echo $short_text; ?></textarea></td>
</tr>
<tr>
<td>
</form>
Then use $_POST['id'] on your processing script to get the id. The intval is an XSS prevention method since id will only be an integer. For other approaches to prevent XSS injections see (this won't stop a SQL injection, parameterized queries should still be used on processing script):
How to prevent XSS with HTML/PHP?
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

Retrieve a variable whos name is has another variable in it

Dunno if the title makes sense, but I have a variable which would to put it in basic terms would be called like this:
$_POST['something'+$variable2]
I have a form which is for editing selected records, this form contains entries for all previously selected records:
<form name="input" action="editcar.php" method="POST">
<input type="submit" value="Yes">
while($row = mysqli_fetch_assoc($result))
{
echo'
</div>
<table style="color:white">
<tr>
<td style="text-align:right">Manufacture:</td><td><input type="text" name="manufacture'.$row['carIndex'].'" value="'.$row['make'].'"></td>
<td style="text-align:right">Model: </td><td><input type="text" name="model'.$row['carIndex'].'" value="'.$row['model'].'"></td>
</tr>
<tr>
<td style="text-align:right">Colour: </td><td><input type="text" name="colour'.$row['carIndex'].'" value="'.$row['colour'].'"></td>
<td style="text-align:right">Reg: </td><td><input type="text" name="reg'.$row['carIndex'].'" value="'.$row['Reg'].'"></td>
</tr>
<tr>
<td style="text-align:right">Price: </td><td><input type="text" name="price'.$row['carIndex'].'" value="'.$row['price'].'"></td>
<td style="text-align:right">Mileage: </td><td><input type="text" name="mileage'.$row['carIndex'].'" value="'.$row['miles'].'"></td>
</tr>
<tr>
<td style="text-align:right">Max MPH: </td><td><input type="text" name="mph'.$row['carIndex'].'" value="'.$row['mph'].'"></td>
<td style="text-align:right">MPG: </td><td><input type="text" name="mpg'.$row['carIndex'].'" value="'.$row['mpg'].'"></td>
</tr>
</table>
</form>
</div> ';
}
?>
</form>
The form is looped for each record previously chosen, to enable mass editing. The isue arouses when I realised I'd have multiple inputs with the same name, so I did:
<input type="text" name="model'.$row['carIndex'].'" value="'.$row['model'].'">
Placing the primary key of the record it was currently tired to on the end of it's name. Which seemed like a logical way to go about things.
However now I need to call these variables to place in the mysql query and I dunno how to do that, or even if I can.
I have the selected records saved in an array so I have:
foreach ($postid as $carID)
{
$query = "stuff";
mysqli_query($db, $query);
}
Each loop has $carID containing the variables that was put on the end of the form input names.
So something like:
$_POST['something'+$variable2]
is all I can think of but doesn't work.
Any method that works for my overall code is welcome not just a solution to the issue I've made.
Actually your way should work. Just replace the + with . in $_POST['something'+$variable2].
My tip is: use an array as name in your html instead:
<input type="text" name="model[]" value="'.$row['model'].'">
On php-Side you can loop through all $_POST['model'] since its an array now.
You can add the index for every entry in your html, too:
<input type="text" name="model['.$row['carIndex'].']" value="'.$row['model'].'">
PHP uses a dot for concatenation, not + like Java and Javascript:
$_POST['something' . $variable2]
Try something like this:
<form ...>
<?php
while($row = mysqli_fetch_assoc(...):
$index = $row['carIndex'];
?>
<input type="text" name="carmodel[<?php echo $index?>][model]" value="<?php echo $row['model'] ?>">
<?php endforeach; ?>
</form>
This way you will have the data stored in $_POST['carmodel'] as an array indexed by carIndex value as the structure of data in $_POST is defined by names of inputs, here you will have names likee carmodel[1][model] for example so then in post it will be in $_POST['carmodel'][1][model]
you can read here as well
How would I create this array structure in an HTML form?

HTML form to update Mysql with PHP (and HTML)

I've been trying to develop a real estate page where people can add listings. I am new to the world of php mysql. I have been over this problem for over a day and can't figure out where the problem is.
I have a form where people can add data. That's good and working. Now I am starting to have a place where people can add / delete / update their info. I am trying to build this step by step.
This is where a user could pull the information. My problem is with the piece of the code:
edit_form.php?idBAR=$row[id].
Full code below.
<table>
<tr>
<td align="center">EDIT DATA</td>
</tr>
<tr>
<td>
<table border="1">
<?php
include"configS_OH.php";//database connection
$order = "SELECT * FROM braaasil_brokerstour.property";
$result = mysql_query($order);
while ($row=mysql_fetch_array($result)){
echo ("<tr><td>$row[id]</td>");
echo ("<td>$row[address]</td>");
echo ("<td>$row[day]</td>");
echo ("<td>$row[hours]</td>");
echo ("<td>Edit</td></tr>");
}
?>
</table>
</td>
</tr>
</table>
Then this tutorial try to pass id through the address bar (I don't know much about php to actually say much)
It tries to upload the data into a new form where a person could edit info.
But I can't load the data into the new form. If I use where id=7, I get the info into the form. But this method of passing the info in the address bar like ?idBAR=8... and then try to catch it in the other code (where id=$idBAR), is not working.
Here is the code:
<table border=1>
<tr>
<td align=center>Form Edit Employees Data</td>
</tr>
<tr>
<td>
<table>
<?php
include "configS_OH.php";//database connection
print $database;
$order = "SELECT * FROM braaasil_brokerstour.property
WHERE id='$idBAR'";
print $idBAR;
$result = mysql_query($order) or die( mysql_error() );
$row = mysql_fetch_array($result);
?>
<form method="post" action="edit_data.php">
<input type="hidden" name="idBAR" value="<?php echo "$row[id]"?>">
<tr>
<td>Address</td>
<td>
<input type="text" name="address"
size="20" value="<?php echo "$row[address]"?>">
</td>
</tr>
<tr>
<td>Date</td>
<td>
<input type="text" name="day" size="40"
value="<?php echo "$row[day]"?>">
</td>
</tr>
<tr>
<td>Time</td>
<td>
<input type="text" name="time" size="40"
value="<?php echo "$row[hours]"?>">
</td>
</tr>
<tr>
<td align="right">
<input type="submit"
name="submit value" value="Edit">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
I tried an tried and tried..
Thank you for your time in advance.
WHERE id='$idBAR'
You haven't assigned $idBAR any value. You need to read it from the $_GET array first:
$idBAR = $_GET['idBAR'];
You should, of course, check that this value exists first, and is acceptable.
I don't see anywhere you have actually used the GET data, just the reference name which is used in GET.
If you first query is working and is getting the $row['id'] value ok - you can verify this when you go to edit_form.php, in your browser URL bar at the top, does it say this:
edit_form.php?idBAR=7
(or whatever number should be there)
If so, then you just need to use the PHP GET. Your data is stored in $_GET[], and in this case, the reference name is idBAR. So your id from your previous page query is sent through the link into your URL, and on your edit_form.php page, you'd use that data as:
$_GET['idBAR']
You can use that, but personally I assign the data to a variable, such as:
$strGetId = $_GET['idBAR'];
Then you can use $strGetId throughout your code.
Also, check things like isset(), empty() etc, just so you know you are working with A) something is actually there, and B) it's not empty etc
if you are putting a variable directly in a string without concatenating, it can't be an array variable; you must concatenate those you also need to surr. so this
echo ("<td>Edit</td></tr>");
should be this
echo ("<td>Edit</td></tr>");
also, it looks like your form is sending data with POST. When you pass form data in the url string after the question mark, that is passing with get.
so...in your form where you want to use that variable, you set it up like this
$idBAR=$_GET['idBAR']; //to get the variable if it was part of the URL
$idBAR=$_POST['idBAR']; //if it was sent with post, as is the case with your form
also, request contains both get and post, so
$idBAR=$_REQUEST['idBAR'];
will work in either case.
The problem is the $row[id] is seen as text just like everything else. You want the value of $row[id]. Instead of
echo ("<td>Edit</td></tr>");
try
echo ("<td>Edit</td></tr>");

PHP Update query not receiving variable already defined in page

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

Only inserts in to database once then fails

I have a small section of code. When the table is empty this code works fine and enters in to the table fine. But then if i try again then this fails with the error?
What am i doing wrong?
Thanks
// On my Function page
function admin(){
connect();
$query = mysql_query("INSERT INTO results
(t_id, pos1, pos2, pos3)
VALUES ('$_POST[t_id]','$_POST[pos1]','$_POST[pos2]','$_POST[pos3]')")
or die ("Error.");
$b = "Updated fine</b></a>.";
return $b;
exit();
}
// Then on my main page
<?php
include ('functions.php');
if (isset($_POST['admin'])){
$admin = admin();
}
?>
<div id="content">
<div id="admin">
<form action="" method="post">
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1">
<tr>
<td width="100%"><?php echo "$admin"; ?></td>
</tr>
<tr>
<td width="100%"><label>Track <input type="text" name="track" size="25" value="<? echo $_POST[t_id]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 1<input type="text" name="pos1" size="25" value="<? echo $_POST[pos1]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 2 <input type="text" name="pos2" size="25" value="<? echo $_POST[pos2]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 3 <input type="text" name="pos3" size="25" value="<? echo $_POST[pos3]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><input class="save" type="submit" value="" name="admin"></td>
</tr>
</table>
</form>
</div>
</div>
Without seeing your table schema, I can only think you have UNIQUE t_id and you want to insert the same ID into it.
Several way to debug:
Use or die ("Error: " . mysql_error()); instead of just or die ("Error.");
Check your table schema: SHOW CREATE TABLE tablename and write it down on your question, so we can see if it's causing error.
It is hard to guess. Maybe you are entering the same values twice, and they happen to violate some unique constraint?
But you make another mistake: you forget to call mysql_real_escape(). That is bad.
Can you tell us of the error? It sounds like you're hitting a primary key violation, perhaps by trying to insert the same id more than once.
That aside, your code is riddled with security holes.
You should not be inserting variables straight from the POST into your query. All I have to do is submit '; DROP DATABASE and I can completely wreck your system.
Additionally, you're injecting values directly from POST into input fields, meaning I can set up a button on my site that submits " <script type='text/javascript'>window.location='http://mysite.com'</script> or something along those lines and take over your page.
This may sound terse, but you should do some googling or pick up a book regarding textbook security issues with websites.
EDIT: Just saw your comment about learning security. My advice is to be proactive about this sort of thing, because being reactive is often too late to fix problems.

Categories