Can I use $_POST & $_GET at the same time? - php

I have a following form:
<form action="doThis.php?warehouse=12" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
</form>
And doThis.php:
$field1 = mysql_real_escape_string($_POST['field1'], $mysql);
$field2 = mysql_real_escape_string($_POST['field2'], $mysql);
$warehouse = $_GET['warehouse'];
if ( !someTableNameValidation($warehouse) ) {
someErrorHandling();
}
$qry = "INSERT INTO table".$warehouse." ( field1, field2 ) VALUES( '$field2', '$field2') ";
$result = #mysql_query($qry, $mysql);
As you can see, I'm using $_POST to get data from the form, and $_GET to get variable $warehouse which is used to indicate table number.
Can I use both $_POST & $_GET at the same time? Is this kind of usage correct?

Yes you could. $_GET['warehouse'] will be taken from the query string, $_POST variables from submitted POST values.

Yes, this is possible. But you could also use a hidden field:
<form action="doThis.php">
<input type="hidden" name="warehouse" value="12" />
<input name="field1" type="text" />
<input name="field2" type="text" />
Please be aware that your code is very vulnerable to sql injections!

Yes I always do that.
Also note you should never use mysql_query. Search for php PDO. Not to mention the awful # for suppressing error

Yes, however it should be:
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$warehouse = $_GET['warehouse'];
$qry = "INSERT INTO table".$warehouse." ( field1, field2 ) VALUES ('".mysql_real_escape_string($field2)."', '".mysql_real_escape_string($field2)."')";
$result = #mysql_query($qry);
(Fixed syntax)

I frequently use POST and GET together, so that the PHP side can know whether it was a normal form submission or via AJAX.
<form action='dest.php'>
.
.
.
vs
ajaxSubmit( 'dest.php?a=1', ... );

Related

POST checkbox name even if its not checked

Is it possible to POST checkbox name even if its not checked?
<input type='checkbox' class='tinyField' name='alert_by_email' value="1" <?PHP echo $alert_by_emailChecked ?> />
foreach ($_POST AS $field => $value)
$sql[] = $field." = '". $value."'";
$sql = implode(' , ',$sql);
$query = "UPDATE user_setup SET ".$sql." WHERE (userID = ".$userID.") " ;
$res = mysql_query($query);
So when I PRINT_R the POST i will get the field, but it will be empty
Array ( [alert_by_email] => '' )
Add this before your checkbox.
<input type='hidden' name='alert_by_email' value="" />
The straight forward answer is no.
The HTML form wont send the checkbox if it's not checked.
However, there are some workarounds:
use js to Generate a hidden input for each checkbox you have, set the value to 0 or '', and whenever you check them, remove the hidden input.
you could simply test if the key exist in the post like so:
if (isset($_POST['alert_by_email']))
In Short, No this is not possible if you are posting FORM without using any Javascript.
Also, Your code may be injected easily as you are relying on user provided column names without validating those. I am posting alternative way to do that. Hope that helps:
Suppose you have this HTML Form:
<form method="POST">
First name:<br />
<input type="text" name="firstname" />
<br />
Last name:<br />
<input type="text" name="lastname" /><br />
<input type="submit" />
</form>
Now, if you want to update values using PHP, your code should be:
<?php
$columnArray = array('firstname' => NULL, 'lastname' => NULL); // This is list of columns which can be updated using form input values (NULL is default value here)
$submittedValues = array_intersect_key($_POST, $columnArray);
// Above code will produce an array like `array('firstname' => 'anyname', 'lastname' => 'anylastname')
//--> Now you can generate your SQL using `$submittedValues`
$sql = array();
foreach ($submittedValues as $field => $value)
{
$sql[] = $field." = '". $value."'";
}
$sqlString = implode(' , ',$sql);
Using this way, hacker will not be able to add extra columns which shouldn't be updated by user i.e. last_login_date or something.

PHP foreach Construct Confusion

I am having a hard time wrapping my head around the foreach construct. I have found numerous examples of course, but I never seem to be able to adapt them to my needs.
Please consider this working example I have:
I am collecting two dates in an HTML form:
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" name="FirstAGMDate" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" name="MinutesInspectedFromDate" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
On submit the values are being pushed to the mysql database with a PDO prepared statement:
if (isset($_POST['submit'])) {
$sql = "UPDATE jobsinglevalues SET Date = :FirstAGMDate WHERE FormId = 0;
UPDATE jobsinglevalues SET Date = :MinutesInspectedFromDate WHERE FormId = 1;";
$sth = $db->prepare($sql);
$sth->execute(array(':FirstAGMDate'=>($_POST['FirstAGMDate']), ':MinutesInspectedFromDate'=>($_POST['MinutesInspectedFromDate'])));
}
This works no problem, but it's not very clever when I need to repeat this for a dozen inputs. What I want to do is achieve this with only one line of sql; looping for each <input type="text" name="Value" />.
How can I place this into a foreach loop?
In my head it works like this:
On submit each input updates the value in the database based on FormId, which increments by 1 each loop starting at 0. FormId is not a primary key, it simply mirrors the order in which the form elements are displayed.
Update - working example
if (isset($_POST['submit'])) {
$FormId = 0;
foreach($_POST['Value'] as $avalue){
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId";
$sth = $db->prepare($sql);
$sth->execute(array(':Value'=>($avalue), ':FormId'=>($FormId)));
++$FormId;
}
}
This seems to logically work to me! Is the correct solution similar? Please let me know if I need to clarify anything.
Thankyou,
Sam
Let's start by making sure all our values are in an array after posted; if you don't care about the keys you can just use name="Values[]", but I'll use name="Value[FirstAGMDate]" etc so we know what key a value belongs to.
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" id="FirstAGMDate" name="Value[FirstAGMDate]" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" id="MinutesInspectedFromDate" name="Value[MinutesInspectedFromDate]" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
Now we can process the posted array of values. If we want to do something with the key, we can use foreach($_POST['Value'] as $akey => $avalue), if we are only interested in the values then foreach($_POST['Value'] as $avalue) suffices.
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId;";
$sth = $db->prepare($sql);
foreach($_POST['Value'] as $akey => $avalue) {
$sth->execute(array(':Value' => $avalue, ':FormId'=> $FormId ));
++$FormId;
}
[edit] As per edit-suggestion by #AravindKishore, creating the prepared statement is better done before the loop. Prepare once, enjoy forever.

scripting $_POST variable on the fly

I have a registration form that allows a user to register as many people as they want. For example I don't know ahead of time if 1 person is registering or if 500 are. So on the server side if I have 3 people registering at once I need to access all the first names of a person by $_POST['first0'] $_POST['first1'] and $_POST['first2']. So here is my database query.
for ($i=0; $i < runners; $i++) {
$query = "INSERT INTO ".$usertable." VALUES (".$_POST['first'.$i].", ".$_POST['last'.$i].", ".$_POST['age'.$i].",
".$_POST['gender'.$i].", ".$_POST['email'.$i]." , ".$_POST['phone'.$i]." , ".$_POST['address'.$i]." ,
".$_POST['city'.$i]." , ".$_POST['state'.$i]." , ".$_POST['zip'.$i]." , ".$_POST['type'.$i]." , ".$_POST['tshirt'.$i].")";
My query is not working so I know my quotes and apostrophes are incorrect would anyone be able to show me the correct way to accomplish this. Any help is appreciated!
First of all, posted data is a lot easier to work with if your form entries use the array syntax, i.e.:
<label>First: <input name="first[]" value="" /></label>
<label>Last: <input name="last[]" value="" /></label>
<label>Age: <input name="age[]" value="" /></label>
<label>Gender:
<input type="radio" name="gender[]" value="m" />Male
<input type="radio" name="gender[]" value="f" />Female
</label>
Then, in your code, values like $_POST['first'] are an array of values.
Secondly, you should look at prepared statements. Observe:
$stmt = $db->prepare('INSERT INTO mytable (first, last, age, gender) VALUES (?, ?, ?, ?)');
foreach ($_POST['first'] as $index => $value) {
$stmt->execute(array(
$value,
$_POST['last'][$index],
$_POST['age'][$index],
$_POST['gender'][$index],
));
}
First of all, you should prevent SQL injection while interacting with database.
Use mysqli_real_escape_string. Here is the updated query.
for ($i=0; $i < runners; $i++) {
$firstname = mysqli_real_escape_string($_POST['first'.$i]);
$lastname = mysqli_real_escape_string($_POST['last'.$i]);
$age = mysqli_real_escape_string($_POST['age'.$i]);
$gender = mysqli_real_escape_string($_POST['gender'.$i]);
$email = mysqli_real_escape_string($_POST['email'.$i]);
$phone = mysqli_real_escape_string($_POST['phone'.$i]);
$address = mysqli_real_escape_string($_POST['address'.$i]);
$city = mysqli_real_escape_string($_POST['city'.$i]);
$state = mysqli_real_escape_string($_POST['state'.$i]);
$zip= mysqli_real_escape_string($_POST['zip'.$i]);
$type= mysqli_real_escape_string($_POST['type'.$i]);
$tshirt= mysqli_real_escape_string($_POST['tshirt'.$i]);
$query = "INSERT INTO ".$usertable." VALUES ('".$firstname."', '".$lastname ."', ".$age .",
'".$gender ."', '".$email ."', ".$phone." , '".$address ."' ,
'".$city."' , '".$state."' , ".$zip." , '".$type."' , '".$tshirt."')";
The better way to do this is instead of using user0, user1, user2, ...
You can actually past the html input text as an array.
e.g:
<!-- first user field -->
<input type="text" name="users[]" />
<!-- second user field -->
<input type="text" name="users[]" />
<!-- third user field -->
<input type="text" name="users[]" />
So your php will look something like this:
$users = $_POST['users'];
foreach ($users as $user) {
insertQuery = "INSERT INTO $userTable VALUES ('".mysqli_escape_string($user)."');
}
Of course the code above is only an example with 1 variable you can apply them to all other variables.
Cheers.
As suggested by #plain jane you are missing a lot of single quotes.
You can use PHP's variable replacement capability like the following. This is much more readable code.
$query = "INSERT INTO $usertable VALUES ('{$_POST['first'.$i]}', '{$_POST['last'.$i]}', '{$_POST['age'.$i]}',
'{$_POST['gender'.$i]}', '{$_POST['email'.$i]}', '{$_POST['phone'.$i]}', '{$_POST['address'.$i]}' ,
'{$_POST['city'.$i]}' , '{$_POST['state'.$i]}' , '{$_POST['zip'.$i]}' , '{$_POST['type'.$i]}' , '{$_POST['tshirt'.$i]}')";
Warning: Your code is vulnerable to SQL injection and can be easily broken with just a single quote in any posted field. even St'Mary as first name will break your code. To prevent this
Please validate/sanitize your posted values
Use Prepared statements instead of direct query string.

PHP post $_GET variable in table field

I'm having some problems trying to post $_GET variables into a table.
Here is my script:
include 'connect.php';
if(isset($_POST['client_name'])) {
$_GET['list']; //these are variables passed through from another page and I want these to post in the same table this page is suppose to post in.
$_GET['list_id'];
$Cname = $_POST['client_name'];
$Cnumber = $_POST['client_number'];
$listid = $_POST['list_id'];
$listname = $_POST['list'];
if(!empty($Cname) && !empty($Cnumber)){
$query = "INSERT INTO clients (id, client_name, client_number, list_name, date_registered, list_id) VALUES ('$userid','$Cname', '$Cnumber', '$listname', now(), '$listid')";
mysql_query($query);
echo '<br />
<br />
You successfully added a new clients to your list View Update';
mysql_close();
}
else {
echo '<script type="text/javascript">alert("Both fields are required");</script>';
}
Whenever I run the script everything else but the listname and list_id is posted in the database table.
I tried assigning the get variables to new variable such as
$listNAME = $_GET['id'];
but even with that I still end up with empty fields in my table
I even tried to use the $_GET variable in the mysql INSERT query and still no luck
Can anyone help me out and give me some advice as to what I can do to solve the empty fields when the script runs.
<form action="addclient.php" method="POST">
Name of Client: <input type="text" name="client_name">
Client's Number: <input type="text" name="client_number" placeholder="1-876-xxx-xxx">
<input type="submit" >
</form>
You say you have $_GET variables, but you are trying to retrieve them as $_POST variables:
$listid = $_POST['list_id'];
$listname = $_POST['list'];
Isn't it the issue? You could also try this to see what's comming in both arrays:
print_r($_GET);
print_r($_POST);
Alternatively, you could use $_REQUEST as it receives either $_GET or $_POST variables.
I say it only to notice .
Please use PDO or mysqli
if you are calling your addclient.php like
http://localhost/addclient.php?list_id=100&list=mylistname
than you must catch both variables in addclient.php
if (isset($_GET['list_id'])) {
$listid = $_GET['list_id'];
$listname = $_GET['list'];
}
and your form
<form action="addclient.php" method="POST">
<input type="hidden" name="list_id" value="$listid">
<input type="hidden" name="list" value="$listname">
Name of Client: <input type="text" name="client_name">
Client's Number: <input type="text" name="client_number" placeholder="1-876-xxx-xxx">
<input type="submit" >
</form>
and after submit
if(isset($_POST['client_name'])) {
$Cname = $_POST['client_name'];
$Cnumber = $_POST['client_number'];
$listid = $_POST['list_id'];
$listname = $_POST['list'];
....
}
and in your insert
VALUES ('$userid','$Cname', '$Cnumber', '$listname', now(), '$listid')
$listid without quotes it's a int(11) .
VALUES ('$userid','$Cname', '$Cnumber', '$listname', now(), $listid)

PHP and MySQL form, what am I doing wrong?

I have a table that has the user ID already in it, but some of the information is missing and that is where I need the user to input it themselves. With the URL of the form I have their ID in it... winnerpage.php?ID=123
I am having troubles getting the code to work. Any help would be great!
This is the code on that winnerpage.php
<form enctype="multipart/form-data" action="winnerpage.php" method="POST">
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
First Name: <input type="text" name="FN"><br />
Last Name: <input type="text" name="LN"><br />
Email: <input type="text" name="EM"><br />
Phone: <input type="text" name="PH"><br />
<input type="submit" name="edit" value="edit"></form> <br>
<?
require_once('mysql_serv_inc.php');
$conn = mysql_connect("$mysql_server","$mysql_user","$mysql_pass");
if (!$conn) die ("ERROR");
mysql_select_db($mysql_database,$conn) or die ("ERROR");
if(isset($_POST['edit']))
{
$sID = addslashes($_POST['ID']);
$sFN = addslashes($_POST['FN']);
$sLN = addslashes($_POST['LN']);
$sEM = addslashes($_POST['EM']);
$sPH = addslashes($_POST['PH']);
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH
WHERE ID=$sID') or die (mysql_error());
echo 'Updated!';
}
$query = "select * from winner order by ID";
$result = mysql_query($query);
?>
<?
while ($link=mysql_fetch_array($result))
{
echo 'Unique ID - Completion Time - First Name - Last Name - Email - Phone<br/>'.$link[ID].' -' .$link[FN].' - '.$link[LN].' - '.$link[EM].' - '.$link[PH].'<br>';
}
?>
1)
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
Where do you get that $ID? Are you doing something like $_GET['ID'] or are you relying on safe_mode being ON? (it's not clear from the code you provided)
(better yet, if(isset($_GET['ID'])) { $ID = (int)$_GET['ID'] }
2) Please don't to that. Don't use addslashes(). Use mysql_real_escape_string() or, even better, prepared statements. Addslashes is not utterly reliable in escaping datas for queries.
sID = (int)$_POST['ID'];
$sFN = mysql_real_escape_string($_POST['FN']);
$sLN = mysql_real_escape_string($_POST['LN']);
$sEM = mysql_real_escape_string($_POST['EM']);
$sPH = mysql_real_escape_string($_POST['PH']);
Also, add 'value=""' to each input field (not mandatory)
3) encapsulate values in query:
mysql_query("UPDATE winner SET FN='".$sFN."', LN='".$sLN."', EM='".$sEM."', PH='".$sPH."' WHERE ID='".$sID."'") or die (mysql_error());
Maybe try:
mysql_query("UPDATE winner SET FN='$sFN', LN='$sLN', EM='$sEM', PH='$sPH' WHERE ID=$sID") or die (mysql_error());
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH WHERE ID=$sID')
the query is encapsulated by single-quotes, so the variables inside will not be parsed.
At first glance I would say that you need:
1) Quote marks around some of the values you are inserting into the table (any strings for example)
2) Quote marks around the names of the fields when you try to echo them out at the end ($link['ID'] for example)

Categories