PHP $_GET and $_POST variables are not working properly - php

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

Related

How to save 'contenteditable' on database

<tr contenteditable>
<td><center><?php echo $nama = $isi['nama']; ?></center> </td>
<td><center><?php echo $jk = $isi['jk']; ?></center> </td>
I have this code,
And I dunno how to save it on my database.
if you guys don't mind, you can check the picture here : http://imagizer.imageshack.us/a/img673/4384/Ww9PKg.jpg
What I suggest is instead of making the table content editable, and allow users to change it, put the data that will be updated on input fields, and post to your PHP script to save:
<form action="/post.php" method="post">
<tr>
<td><input type="text" name="nama-0" value="<?php echo $nama = $isi['nama']; ?>"></td>
<td><input type="text" name="jk-0" value="<?php echo $jk = $isi['jk']; ?>"></td>
</tr>
</form>
But if you still need to use the table without the input elements (I've no idea why that'd be required) then use javascript to extract the values from table, and then submit to your PHP script.

Variable is not usind in link?

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.

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

hide a hidden input value when a submit button is clicked (php/jquery)

Ok, so my problem is this:
I have a form that asks for a First Name, Last Name, and a City. The user clicks submit and then the information is displayed into this table:
<p>You entered the following data:</p>
<form action="1.php" method="post">
<input type="hidden" name="action" value="update">
<input type="hidden" name="city" value="<?php echo $user->get_city(); ?>">
<table>
<tr>
<th>First Name:</th>
<td><?php echo $user->get_fname(); ?></td>
<td><input type="button" id="edit_fname" value="Edit"></td>
<td><input type="text" id="fname" name="fname" size="20"></td>
<td><input type="hidden" id="valf" name="val" value="fname">
<input type="hidden" id="lnf" name="lname" value="<?php echo $user->get_lname(); ?>">
<input type="submit" id="subfn" value="Submit"></td>
</tr>
<tr>
<th>Last Name:</th>
<td><?php echo $user->get_lname(); ?></td>
<td><input type="button" id="edit_lname" value="Edit"></td>
<td><input type="text" id="lname" name="lname" size="20"></td>
<td><input type="hidden" id="vall" name="val" value="lname">
<input type="hidden" id="fnf" name="fname" value="<?php echo $user->get_fname(); ?>">
<input type="submit" id="subln" value="Submit"></td>
</tr>
<tr>
<th align="right">City:</th>
<td><?php echo $user->get_city(); ?></td>
<td> </td>
</tr>
</table>
</form>
So, when the user clicks the edit button a text box is displayed along with a submit button, and depending on if it's the first name edit or last name edit, I have the proper hidden values to send along with the form. The only problem is that no matter what, the hidden input 'val' is set to 'lname' even when you click the Submit button for the first name field.
Here is the jquery:
$().ready = function() {
$('#fname').hide();
$('#lname').hide();
$('#subfn').hide(); // submit button for first name
$('#subln').hide(); // submit button for last name
$('#valf').hide(); // hidden value for fname so we know to post lname
$('#vall').hide(); // hidden value for lname so we know to post fname
$('#lnf').hide(); // hidden value to post last name when first name edit submit
$('#fnf').hide(); // hidden value to post first name when last name edit submit
$("#edit_fname").click(function() {
$('#fname').show();
$('#subfn').show();
$('#valf').show();
$('#lnf').show();
if ($('#lname').show) { // if last name edit is showing, hide it
$('#lname').hide();
$('#subln').hide();
$('#vall').hide();
$('#fnf').hide();
}
});
$("#edit_lname").click(function() {
$('#lname').show();
$('#subln').show();
$('#vall').show();
$('#fnf').show();
if ($('#fname').show()) { // if first name edit is showing, hide it
$('#fname').hide();
$('#subfn').hide();
$('#valf').hide();
$('#lnf').hide();
}
});
}();
And here is the PHP for when the Submit button is clicked and changes the 'action' to 'update':
case 'update':
$val = $_POST['val'];
if ($val == 'fname') {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$city = $_POST['city'];
$user = new User($fname, $lname, $city);
break;
}
else if ($val == 'lname') {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$city = $_POST['city'];
$user = new User($fname, $lname, $city);
break;
}
I tested to see what $val is and it seems to be stuck on 'lname' no matter what. So, I think there is a problem with my jQuery code, or the problem is that the last name 'val' value is being sent no matter what, which it shouldn't be because I have it ID'd to be hidden when the first name button is clicked.
This is all experimental to help me learn OOP. Obviously this is not production code at all. I am currently a 1st year student towards my Associates of Applied Science Degree and have many more years until I get the bachelors in computer science. This isn't even a part of a class...I'm just bored and really enjoy programming.
So, think anyone can help? Sorry for such a long post!
Here is why. See the following two lines of code
<td><input type="hidden" id="valf" name="val" value="fname">
.....
<td><input type="hidden" id="vall" name="val" value="lname">
Those define a hidden field named val first with value fname and then with value lname. Even when you are giving them different IDs their names are still the same. And nowhere in your jquery code are you changing the value of val that is why it always remains lname.
You have to change that value depending upon your logic somewhere. You can use following jQuery selector
$("input[type='hidden'][name='val']")
Edit
So instead of this
$('#valf').show();
You can write
$("input[type='hidden'][name='val']").val("fname");
And instead of this
$('#vall').show();
You can write
$("input[type='hidden'][name='val']").val("lname");
You have two different fields with name="val" in the same form. PHP reads each of these in sequence and the second value clobbers (overwrites) the first one, leaving you with just the last value in the $_GET array element.
You can submit multiple values under the same name by specifying the variable name with [] on the end of it. This tells PHP that it's an array element, just like you would use $array[] = "new element"; in your normal code to add an element to an array.
Even using the array syntax wouldn't help you here though, since both values would be passed to the server every time you submitted the form. If you only want one section or the other to be submitted, then they need to be separate forms.

Categories